Spring MVC 學習筆記 json格式的輸入和輸出
阿新 • • 發佈:2018-12-22
Spring mvc處理json需要使用jackson的類庫,因此為支援json格式的輸入輸出需要先修改pom.xml增加jackson包的引用
<!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>1.8.1</version> </dependency>
先修改之前的helloworld.jsp,增加客戶端json格式的資料輸入。
var cfg = { type: 'POST', data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}), dataType: 'json', contentType:'application/json;charset=UTF-8', success: function(result) { alert(result.success); } };function doTestJson(actionName){ cfg.url = actionName; $.ajax(cfg);}
根據前面的分析,在spring mvc中解析輸入為json格式的資料有兩種方式 1:使用@RequestBody來設定輸入
@RequestMapping("/json1") @ResponseBody public JsonResult testJson1(@RequestBody User u){ log.info("get json input from request body annotation"); log.info(u.getUserName()); returnnew JsonResult(true,"return ok");}
2:使用HttpEntity來實現輸入繫結
@RequestMapping("/json2") public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u){ log.info("get json input from HttpEntity annotation"); log.info(u.getBody().getUserName()); ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>( new JsonResult(true,"return ok"),HttpStatus.OK); return responseResult;}
Json格式的輸出也對應有兩種方式 1:使用@responseBody來設定輸出內容為context body 2:返回值設定為ResponseEntity<?>型別,以返回context body 另外,第三種方式是使用ContentNegotiatingViewResolver來設定輸出為json格式,需要修改servlet context配置檔案如下
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> </map> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> <property name="ignoreAcceptHeader" value="true" /> </bean>
但這種格式的輸出會返回{model類名:{內容}} 的json格式, 例如,以下程式碼
@RequestMapping("/json3.json") public JsonResult testJson3(@RequestBody User u){ log.info("handle json output from ContentNegotiatingViewResolver"); return new JsonResult(true,"return ok"); }
期望的返回是 {success:true,message:”return ok”}; 但實際返回的卻是 {"jsonResult":{"success":true,"msg":"return ok"}} 原因是MappingJacksonJsonView中對返回值的處理未考慮modelMap中只有一個值的情況,直接是按照mapName:{mapResult}的格式來返回資料的。 修改方法,過載MappingJacksonJsonView類並重寫filterModel方法如下
protected Object filterModel(Map<String, Object> model) { Map<?, ?> result = (Map<?, ?>) super.filterModel(model); if (result.size() == 1) { return result.values().iterator().next(); } else { return result; } }
對應的ContentNegotiatingViewResolver修改如下
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> </map> </property> <property name="defaultViews"> <list> <bean class="net.zhepu.json.MappingJacksonJsonView" /> </list> </property> <property name="ignoreAcceptHeader" value="true" /> </bean>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>