springMvc注解之@ResponseBody和@RequestBody
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                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的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 明清美文四卷本(共四册)
- 下一篇: H5js的一些好玩的东西
