@ResponseBody介紹
@ResponseBody
是一個Spring框架中的注解,主要用于Web開發,特別是在Spring MVC框架中。它的核心作用是改變Spring MVC處理HTTP請求響應的行為,使得從控制器方法返回的數據直接寫入HTTP響應體(Response Body)中,而不是像默認行為那樣去渲染一個視圖模板(如JSP、Thymeleaf等)。這在構建RESTful API或者需要直接向客戶端返回JSON、XML等數據格式時非常有用。
@ResponseBody源碼
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {}
源代碼截圖
@ResponseBody屬性介紹
沒有屬性,哈哈哈。
@ResponseBody注解使用場景
-
返回JSON或XML響應:當你需要從控制器方法返回JSON或XML格式的數據,而不是傳統的HTML視圖時,可以使用
@ResponseBody
來指示Spring MVC將返回值自動轉換為JSON或XML格式。 -
RESTful Web服務:在構建RESTful Web服務時,通常需要返回JSON或XML格式的響應。使用
@ResponseBody
可以非常方便地實現這一點,而不需要編寫額外的代碼來進行數據轉換。 -
簡單文本響應:除了JSON和XML,
@ResponseBody
還可以用于返回純文本響應,例如返回一個簡單的字符串或數字。 -
避免視圖解析:在某些情況下,你可能不希望Spring MVC進行視圖解析,而是直接返回方法的返回值。使用
@ResponseBody
可以避免Spring MVC查找和解析視圖。 -
自定義響應:如果你需要自定義響應頭或者狀態碼,并且希望響應體包含特定的數據,
@ResponseBody
可以與@RequestMapping
或其他HTTP特定注解結合使用來實現這一需求。 -
異步請求處理:在處理異步請求時,可以使用
@ResponseBody
來返回異步處理的結果,例如使用DeferredResult
或Callable
返回一個異步的結果。 -
減少模板的使用:在某些情況下,可能不需要使用Spring的視圖模板(如Thymeleaf、JSP等),而是直接返回業務數據。
@ResponseBody
可以幫助減少對模板引擎的依賴。 -
與
@RestController
結合使用:@RestController
是@Controller
和@ResponseBody
的快捷方式,用于指示該控制器類中的所有方法都返回響應體而不是視圖。這在編寫純RESTful控制器時非常有用。 -
API開發:在開發API時,經常需要返回結構化數據,
@ResponseBody
使得返回JSON或XML格式的數據變得簡單直接。 -
前端與后端分離:在現代Web開發中,前端和后端分離是一種常見的架構模式。
@ResponseBody
使得后端可以專注于提供數據,而前端則可以自由地選擇如何展示這些數據。
@ResponseBody測試示例代碼
示例代碼 一
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseBody;@RestController
public class MyController {@GetMapping("/hello")@ResponseBodypublic String sayHello() {return "Hello, World!";}@GetMapping("/user")@ResponseBodypublic User getUser() {User user = new User();user.setName("程序員食堂大叔");user.setAge(25);return user;}
}
示例代碼二(@ResponseBody注解返回XML)
配置中包含了處理XML的轉換器
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new Jaxb2RootElementHttpMessageConverter());}
}
創建支持XML序列化的Java類使用JAXB注解
import javax.xml.bind.annotation.XmlRootElement;@Data
@XmlRootElement
public class DemoData {private String name;private String description;}
創建TestController
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;@RestController
public class TestController {@GetMapping(value = "/demo/xml/Data", produces = "application/xml")@ResponseBodypublic MyData getDemoXmlData() {DemoData data = new DemoData ();data.setName("demo");data.setDescription("This is an example data.");return data;}
}