从Spring3.1之后,开始推荐使用RequestMappingHandlerMapping和RequestMappingHandlerAdapter来进行方法映射,在controller里支持使用@RequestBody注解 (从2.5开始应该就支持的)
要使用Spring提供的自动将requestbody里的json字符串的entity 转换为对应的对象实例,需要增加messageconverter,默认没有MappingJackson2HttpMessageConverter
<serveletname>-servlet.xml 配置:
<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
>
</bean>
<bean
>
<property>
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
并添加依赖的包:
jackson-annotations-2.0.5.jar
jackson-databind-2.0.5.jar
jackson-core-2.0.5.jar
以上是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";
}
用apache的 HttpClient包测试:
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();
}
Spring 的详细介绍:请点这里
Spring 的下载地址:请点这里
相关阅读:
基于 Spring 设计并实现 RESTful Web Services
Spring-3.2.4 + Quartz-2.2.0集成实例
Spring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码