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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

springMvc注解之@ResponseBody和@RequestBody

發布時間:2025/3/15 c/c++ 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springMvc注解之@ResponseBody和@RequestBody 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

簡介

springmvc對json的前后臺傳輸做了很好封裝,避免了重復編碼的過程,下面來看看常用的@ResponseBody和@RequestBody注解

添加依賴

springmvc對json的處理依賴jackson

<dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-core-asl</artifactId><version>1.9.11</version> </dependency> <dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.11</version> </dependency>

xml配置

<mvc:annotation-driven />//不要忘了命名空間配置

@ResponseBody

如果傳輸的是單層json對象,我們后臺可以直接用 @RequestParam接收

$.ajax({type : "post",dataType : "json",url : "/testRequestBody",data:{name:"韋德",age:35},success : function(result) {} }); @RequestMapping("/testRequestBody") public String testRequestBody(@RequestParam Map<String, Object> map) {System.out.println(map);// {name=韋德, age=35}return "index"; }

如果傳輸的是多層嵌套json對象,這個時候會就會出現數據丟失問題

@ResponseBody很好的解決了這個問題,它會把前臺傳輸過來的json轉化為后臺對應的對象

$.ajax({type : "post",dataType : "json",url : "/testRequestBody",contentType:"application/json", data:JSON.stringify({name:"韋德",win:[2006,2012,2013],age:35}),success : function(result) {} }); @RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody Map<String, Object> map) {System.out.println(map);//{name=韋德, win=[2006, 2012, 2013], age=35}return "index"; }

需要注意的是前臺需要指定contentType為"application/json"

同時要把json對象轉化為String,否則后臺不能識別

@ResponseBody

ajax請求返回json格式,往常我們可以這樣做

private void writeJson(HttpServletResponse response, Object object) {String json = JSON.toJSONString(object);response.setCharacterEncoding("UTF-8");response.setContentType("application/json; charset=utf-8");PrintWriter out = null;try {out = response.getWriter();out.write(json);} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {out.close();}} }

這個時候 @ResponseBody就派上用場了,只需要一個注解,全部搞定

$.ajax({type : "post",dataType : "json",url : "/testResponseBody",success : function(result) {console.info(result);} }); @RequestMapping("/testResponseBody") @ResponseBody public Map<String, Object> testRequestBody() {Map<String, Object> result = new HashMap<String, Object>();result.put("name", "韋德");result.put("age", 35);return result; }

前臺console輸出

{"age": 35,"name": "韋德" }

總結

在網上看到很不錯的流程圖,作為總結吧

轉載于:https://www.cnblogs.com/zhaoyanhaoBlog/p/9357395.html

總結

以上是生活随笔為你收集整理的springMvc注解之@ResponseBody和@RequestBody的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。