從 Spring 3.1 起,官方推薦改用 RequestMappingHandlerMapping 與 RequestMappingHandlerAdapter 來做方法映射,Controller 裡也支援 @RequestBody 註解(實際上 2.5 就已經支援了)。
要讓 Spring 自動把 request body 中的 json 字串轉成對應的物件實例,必須註冊 message converter,而預設並沒有 MappingJackson2HttpMessageConverter。在 <servletname>-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 2.x 需要三個 jar,缺一不可:
jackson-annotations-2.0.5.jar jackson-databind-2.0.5.jar jackson-core-2.0.5.jar
下載處在 FasterXML 的 Jackson 官方 wiki。值得注意的是,舊的 1.x 只需要兩個包(例如 jackson-core-asl-1.5.6.jar 與 jackson-mapper-asl-1.5.6.jar),2.x 拆得更細,漏掉任何一個都會在執行期出問題。
@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();
}
這裡最容易忽略的是 Content-Type 必須明確標成 application/json,否則 Spring 找不到合適的 converter,就會直接拒絕。