從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
jackson-core-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";
}
用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 的下載地址:請點這裡