从|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.5.jar
jackson-databind-2.0.5.jar
下载地址:http://wiki.fasterxml.com/JacksonDownload
以上是jackson最新的三个包,一个不能少,原来的1.x版本只有两个包 (如:jackson-core-asl-1.5.6.jar jackson-mapper-asl-1.5.6.jar)
Controller里面的方法:
@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(); }