一、@ResponseBody,@RequestBody和HttpMessageConverter
Spring 3.X系列增加了新註解@ResponseBody,@RequestBody@RequestBody 將HTTP請求正文轉換爲適合的HttpMessageConverter對象。
@ResponseBody 將內容或對象作爲 HTTP 響應正文返回,並調用適合HttpMessageConverter的Adapter轉換對象,寫入輸出流。
HttpMessageConverter接口,需要開啓<mvc:annotation-driven />。
AnnotationMethodHandlerAdapter將會初始化7個轉換器,可以通過調用AnnotationMethodHandlerAdapter的getMessageConverts()方法來獲取轉換器的一個集合 List<HttpMessageConverter>
引用:
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
可以理解爲,只要有對應協議的解析器,你就可以通過幾行配置,幾個註解完成協議——對象的轉換工作!
PS:Spring默認的json協議解析由Jackson完成。
二、servlet.xml配置
Spring的配置文件,簡潔到了極致,對於當前這個需求只需要三行核心配置: copy
三、pom.xml配置
四、代碼實現
- @Controller
- public class PersonController {
- /**
- * 查詢個人信息
- *
- * @param id
- * @return
- */
- @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)
- public @ResponseBody
- Person porfile(@PathVariable int id, @PathVariable String name,
- @PathVariable boolean status) {
- return new Person(id, name, status);
- }
- /**
- * 登錄
- *
- * @param person
- * @return
- */
- @RequestMapping(value = "/person/login", method = RequestMethod.POST)
- public @ResponseBody
- Person login(@RequestBody Person person) {
- return person;
- }
- }
備註:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method
= RequestMethod.GET)中的{id}/{name}/{status}與@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一對應,按名匹配。 這是restful式風格。
如果映射名稱有所不一,可以參考如下方式:
- @RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)
- public @ResponseBody
- Person porfile(@PathVariable("id") int uid) {
- return new Person(uid, name, status);
- }
GET模式下,這裏使用了@PathVariable綁定輸入參數,非常適合Restful風格。因爲隱藏了參數與路徑的關係,可以提升網站的安全性,靜態化頁面,降低惡意攻擊風險。
POST模式下,使用@RequestBody綁定請求對象,Spring會幫你進行協議轉換,將Json、Xml協議轉換成你需要的對象。
@ResponseBody可以標註任何對象,由Srping完成對象——協議的轉換。
做個頁面測試下:
Table
五、常見錯誤
POST操作時,我用$.post()方式,屢次失敗,一直報各種異常:
引用
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
直接用$.post()直接請求會有點小問題,儘管我標識爲json協議,但實際上提交的ContentType還是application/x-www-form-urlencoded。需要使用$.ajaxSetup()標示下ContentType。