spring-boot注解详解(二)
@ResponseBody
作用:
該注解用于將Controller的方法返回的對(duì)象,通過適當(dāng)?shù)腍ttpMessageConverter轉(zhuǎn)換為指定格式后,寫入到Response對(duì)象的body數(shù)據(jù)區(qū)。使用時(shí)機(jī):
返回的數(shù)據(jù)不是html標(biāo)簽的頁(yè)面,而是其他某種格式的數(shù)據(jù)時(shí)(如json、xml等)使用; @RequestMapping("/login")@ResponseBodypublic User login(User user){return user;}User字段:userName pwd 那么在前臺(tái)接收到的數(shù)據(jù)為:’{“userName”:“xxx”,“pwd”:“xxx”}’
效果等同于如下代碼:
@RestController
@RestController注解相當(dāng)于@ResponseBody + @Controller合在一起的作用。
如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁(yè)面,或者h(yuǎn)tml,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。
如果需要返回到指定頁(yè)面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁(yè)面,則需要在對(duì)應(yīng)的方法上加上@ResponseBody注解。
例如:
1.使用@Controller 注解,在對(duì)應(yīng)的方法上,視圖解析器可以解析return 的jsp,html頁(yè)面,并且跳轉(zhuǎn)到相應(yīng)頁(yè)面
若返回json等內(nèi)容到頁(yè)面,則需要加@ResponseBody注解
@CrossOrigin @Controller public class FileUploadController {//跳轉(zhuǎn)到上傳文件的頁(yè)面 @RequestMapping(value="/gouploadimg", method = RequestMethod.GET) public String goUploadImg() { //跳轉(zhuǎn)到 templates 目錄下的 uploadimg.html return "uploadimg"; }//處理文件上傳 @RequestMapping(value="/testuploadimg", method = RequestMethod.POST) public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) { System.out.println("調(diào)用文件上傳方法"); String contentType = file.getContentType(); String fileName = file.getOriginalFilename();2.@RestController注解,相當(dāng)于@Controller+@ResponseBody兩個(gè)注解的結(jié)合,返回json數(shù)據(jù)不需要在方法前面加@ResponseBody注解了,但使用@RestController這個(gè)注解,就不能返回jsp,html頁(yè)面,視圖解析器無法解析jsp,html頁(yè)面
@CrossOrigin @RestController /* @Controller + @ResponseBody*/ public class HospitalController {//注入Service服務(wù)對(duì)象@Autowiredprivate HospitalService hospitalService;/*** 查詢所有醫(yī)院信息(未分頁(yè))*/@RequestMapping(value = "findAllHospital",method = RequestMethod.GET)public List<Hospital> findAllHospital(){List<Hospital> hospitalList= hospitalService.findAllHospital();return hospitalList;}總結(jié)
以上是生活随笔為你收集整理的spring-boot注解详解(二)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中文语料库有哪些
- 下一篇: npy文件过大 如何处理