日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

spring-boot注解详解(二)

發(fā)布時(shí)間:2023/12/10 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring-boot注解详解(二) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

@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”}’
效果等同于如下代碼:

@RequestMapping("/login")public void login(User user, HttpServletResponse response){response.getWriter.write(JSONObject.fromObject(user).toString());}

@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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。