@ResponseBody
作用:
該注解用于將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。
使用時機:
返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用;
@RequestMapping("/login")@ResponseBodypublic User login(User user){return user;}
User字段:userName pwd 那么在前臺接收到的數據為:’{“userName”:“xxx”,“pwd”:“xxx”}’
效果等同于如下代碼:
@RequestMapping("/login")public void login(User user, HttpServletResponse response){response.getWriter.write(JSONObject.fromObject(user).toString());}
@RestController
@RestController注解相當于@ResponseBody + @Controller合在一起的作用。
-
如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內容就是Return 里的內容。
-
如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody注解。
例如:
1.使用@Controller 注解,在對應的方法上,視圖解析器可以解析return 的jsp,html頁面,并且跳轉到相應頁面
若返回json等內容到頁面,則需要加@ResponseBody注解
@CrossOrigin
@Controller
public class FileUploadController {//跳轉到上傳文件的頁面
@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
//跳轉到 templates 目錄下的 uploadimg.html
return "uploadimg";
}//處理文件上傳
@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
System.out.println("調用文件上傳方法");
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
2.@RestController注解,相當于@Controller+@ResponseBody兩個注解的結合,返回json數據不需要在方法前面加@ResponseBody注解了,但使用@RestController這個注解,就不能返回jsp,html頁面,視圖解析器無法解析jsp,html頁面
@CrossOrigin
@RestController /* @Controller + @ResponseBody*/
public class HospitalController {//注入Service服務對象@Autowiredprivate HospitalService hospitalService;/*** 查詢所有醫院信息(未分頁)*/@RequestMapping(value = "findAllHospital",method = RequestMethod.GET)public List<Hospital> findAllHospital(){List<Hospital> hospitalList= hospitalService.findAllHospital();return hospitalList;}