Spring MVC 中的 @ResponseBody,@RequestBody,@PathVariable

一、@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

  1. <context:component-scan base-package="org.zlex.json.controller" />  
  2. <context:annotation-config />  
  3. <mvc:annotation-driven />  

三、pom.xml配置  

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <dependency>  
  2.         <groupId>org.springframework</groupId>  
  3.         <artifactId>spring-webmvc</artifactId>  
  4.         <version>3.1.2.RELEASE</version>  
  5.         <type>jar</type>  
  6.         <scope>compile</scope>  
  7.     </dependency>  
  8.     <dependency>  
  9.         <groupId>org.codehaus.jackson</groupId>  
  10.         <artifactId>jackson-mapper-asl</artifactId>  
  11.         <version>1.9.8</version>  
  12.         <type>jar</type>  
  13.         <scope>compile</scope>  
  14.     </dependency>  
  15.     <dependency>  
  16.         <groupId>log4j</groupId>  
  17.         <artifactId>log4j</artifactId>  
  18.         <version>1.2.17</version>  
  19.         <scope>compile</scope>  
  20.     </dependency>  

四、代碼實現 

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. public class Person implements Serializable {  
  2.   
  3.     private int id;  
  4.     private String name;  
  5.     private boolean status;  
  6.   
  7.     public Person() {  
  8.         // do nothing  
  9.     }  
  10. }  
  1. @Controller  
  2. public class PersonController {  
  3.   
  4.     /** 
  5.      * 查詢個人信息 
  6.      *  
  7.      * @param id 
  8.      * @return 
  9.      */  
  10.     @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
  11.     public @ResponseBody  
  12.     Person porfile(@PathVariable int id, @PathVariable String name,  
  13.             @PathVariable boolean status) {  
  14.         return new Person(id, name, status);  
  15.     }  
  16.   
  17.     /** 
  18.      * 登錄 
  19.      *  
  20.      * @param person 
  21.      * @return 
  22.      */  
  23.     @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
  24.     public @ResponseBody  
  25.     Person login(@RequestBody Person person) {  
  26.         return person;  
  27.     }  
  28. }  

備註:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}與@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一對應,按名匹配。 這是restful式風格。 
如果映射名稱有所不一,可以參考如下方式: 

  1. @RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
  2. public @ResponseBody  
  3. Person porfile(@PathVariable("id"int uid) {  
  4.     return new Person(uid, name, status);  
  5. }  

GET模式下,這裏使用了@PathVariable綁定輸入參數,非常適合Restful風格。因爲隱藏了參數與路徑的關係,可以提升網站的安全性,靜態化頁面,降低惡意攻擊風險。
POST模式下,使用@RequestBody綁定請求對象,Spring會幫你進行協議轉換,將Json、Xml協議轉換成你需要的對象。
@ResponseBody可以標註任何對象,由Srping完成對象——協議的轉換。

做個頁面測試下: 

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. $(document).ready(function() {  
  2.     $("#profile").click(function() {  
  3.         profile();  
  4.     });  
  5.     $("#login").click(function() {  
  6.         login();  
  7.     });  
  8. });  
  9. function profile() {  
  10.     var url = 'http://localhost:8080/spring-json/json/person/profile/';  
  11.     var query = $('#id').val() + '/' + $('#name').val() + '/'  
  12.             + $('#status').val();  
  13.     url += query;  
  14.     alert(url);  
  15.     $.get(url, function(data) {  
  16.         alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
  17.                 + data.status);  
  18.     });  
  19. }  
  20. function login() {  
  21.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
  22.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
  23.     alert(mydata);  
  24.     $.ajax({  
  25.         type : 'POST',  
  26.         contentType : 'application/json',  
  27.         url : 'http://localhost:8080/spring-json/json/person/login',  
  28.         processData : false,  
  29.         dataType : 'json',  
  30.         data : mydata,  
  31.         success : function(data) {  
  32.             alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
  33.                     + data.status);  
  34.         },  
  35.         error : function() {  
  36.             alert('Err...');  
  37.         }  
  38.     });  

Table 

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <table>  
  2.     <tr>  
  3.         <td>id</td>  
  4.         <td><input id="id" value="100" /></td>  
  5.     </tr>  
  6.     <tr>  
  7.         <td>name</td>  
  8.         <td><input id="name" value="snowolf" /></td>  
  9.     </tr>  
  10.     <tr>  
  11.         <td>status</td>  
  12.         <td><input id="status" value="true" /></td>  
  13.     </tr>  
  14.     <tr>  
  15.         <td><input type="button" id="profile" value="Profile——GET" /></td>  
  16.         <td><input type="button" id="login" value="Login——POST" /></td>  
  17.     </tr>  
  18. </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。 

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. function login() {  
  2.     var mydata = '{"name":"' + $('#name').val() + '","id":"'  
  3.             + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
  4.     alert(mydata);  
  5.     $.ajaxSetup({  
  6.         contentType : 'application/json'  
  7.     });  
  8.     $.post('http://localhost:8080/spring-json/json/person/login', mydata,  
  9.             function(data) {  
  10.                 alert("id: " + data.id + "\nname: " + data.name  
  11.                         + "\nstatus: " + data.status);  
  12.             }, 'json');  
  13. };  
發佈了22 篇原創文章 · 獲贊 26 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章