SpringMVC層跟JSon結合,幾乎不須要作什麼配置,代碼實現也至關簡潔。不再用爲了組裝協議而勞煩辛苦了!1、Spring註解@ResponseBody,@RequestBody和HttpMessageConverterSpring 3.X系列增長了新註解@ResponseBody,@RequestBodyhtml
@RequestBody 將HTTP請求正文轉換爲適合的HttpMessageConverter對象。java
@ResponseBody 將內容或對象做爲 HTTP 響應正文返回,並調用適合HttpMessageConverter的Adapter轉換對象,寫入輸出流。web
HttpMessageConverter接口,須要開啓<mvc:annotation-driven />。AnnotationMethodHandlerAdapter將會初始化7個轉換器,能夠經過調用AnnotationMethodHandlerAdapter的getMessageConverts()方法來獲取轉換器的一個集合 List<HttpMessageConverter>ajax
引用spring
ByteArrayHttpMessageConverter StringHttpMessageConverter ResourceHttpMessageConverter SourceHttpMessageConverter XmlAwareFormHttpMessageConverter Jaxb2RootElementHttpMessageConverter MappingJacksonHttpMessageConverterjson
能夠理解爲,只要有對應協議的解析器,你就能夠經過幾行配置,幾個註解完成協議——對象的轉換工做! PS:Spring默認的json協議解析由Jackson完成。2、servlet.xml配置Spring的配置文件,簡潔到了極致,對於當前這個需求只須要三行核心配置:安全
Xml代碼restful
<context:component-scan base-package="org.zlex.json.controller" />mvc
<context:annotation-config />app
<mvc:annotation-driven />
3、pom.xml配置閒言少敘,先說依賴配置,這裏以Json+Spring爲參考:pom.xml
Xml代碼
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.2.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.8</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> <scope>compile</scope> </dependency>
主要須要spring-webmvc、jackson-mapper-asl兩個包,其他依賴包Maven會幫你完成。至於log4j,我仍是須要看日誌嘛。 包依賴圖:至於版本,看項目須要吧!4、代碼實現域對象:
Java代碼
public class Person implements Serializable { private int id; private String name; private boolean status; public Person() { // do nothing } }
這裏須要一個空構造,由Spring轉換對象時,進行初始化。@ResponseBody,@RequestBody,@PathVariable 控制器:
Java代碼
@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完成對象——協議的轉換。
作個頁面測試下:JS
$(document).ready(function() { $("#profile").click(function() { profile(); }); $("#login").click(function() { login(); }); }); function profile() { var url = 'http://localhost:8080/spring-json/json/person/profile/'; var query = $('#id').val() + '/' + $('#name').val() + '/' + $('#status').val(); url += query; alert(url); $.get(url, function(data) { alert("id: " + data.id + "\nname: " + data.name + "\nstatus: " + data.status); }); } function login() { var mydata = '{"name":"' + $('#name').val() + '","id":"' + $('#id').val() + '","status":"' + $('#status').val() + '"}'; alert(mydata); $.ajax({ type : 'POST', contentType : 'application/json', url : 'http://localhost:8080/spring-json/json/person/login', processData : false, dataType : 'json', data : mydata, success : function(data) { alert("id: " + data.id + "\nname: " + data.name + "\nstatus: " + data.status); }, error : function() { alert('Err...'); } });
Table
Html代碼
<table> <tr> <td>id</td> <td><input id="id" value="100" /></td> </tr> <tr> <td>name</td> <td><input id="name" value="snowolf" /></td> </tr> <tr> <td>status</td> <td><input id="status" value="true" /></td> </tr> <tr> <td><input type="button" id="profile" value="Profile——GET" /></td> <td><input type="button" id="login" value="Login——POST" /></td> </tr> </table>
4、常見錯誤 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。
Js代碼
function login() { var mydata = '{"name":"' + $('#name').val() + '","id":"' + $('#id').val() + '","status":"' + $('#status').val() + '"}'; alert(mydata); $.ajaxSetup({ contentType : 'application/json' }); $.post('http://localhost:8080/spring-json/json/person/login', mydata, function(data) { alert("id: " + data.id + "\nname: " + data.name + "\nstatus: " + data.status); }, 'json'); };