配置Spring支援自動json格式資料轉換
阿新 • • 發佈:2019-01-29
從|Spring3.1之後,開始推薦使用RequestMappingHandlerMapping和RequestMappingHandlerAdapter來進行方法對映,
在controller裡支援使用@RequestBody註解 (從2.5開始應該就支援的)
要使用Spring提供的自動將requestbody裡的json字串的entity 轉換為對應的物件例項,
需要增加messageconverter,預設沒有MappingJackson2HttpMessageConverter
<serveletname>-servlet.xml 配置:
<!-- ②:啟動Spring MVC的註解功能,完成請求和註解POJO的對映 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> </bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </list> </property> </bean>
並新增依賴的包:
jackson-annotations-2.0.2.jar
jackson-databind-2.0.2.jar
下載地址:請搜尋我的資源分享,提供連結資源被刪~
以上是jackson最新的三個包,一個不能少,原來的1.x版本只有兩個包 (如:jackson-core-asl-1.5.6.jar jackson-mapper-asl-1.5.6.jar)
Controller裡面的方法:
用apache的 HttpClient包測試:@RequestMapping(value = "/db/addUser.do", method = RequestMethod.POST) @ResponseBody public String addUser(@RequestBody User user) { log.info(user.toString()); return "success"; }
HttpPost post = new HttpPost(URL); // 向伺服器寫json StringEntity se = new StringEntity(user, Consts.UTF_8); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, Consts.UTF_8.toString())); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); post.setEntity(se); // post.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"); DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(post); System.out.println(response.getStatusLine().toString()); } catch (ClientProtocolException e) { e.printStackTrace(); post.abort(); } catch (IOException e) { e.printStackTrace(); post.abort(); }