javascript
Spring REST
示例實(shí)現(xiàn)
1. 請(qǐng)求REST接口返回類轉(zhuǎn)換的JSON或XML數(shù)據(jù)
2. POST JSON數(shù)據(jù)到REST接口自動(dòng)轉(zhuǎn)為類數(shù)據(jù)
服務(wù)端
Bean
package com.qunar.bean;import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;/*** Created with IntelliJ IDEA.* User: zhenwei.liu* Date: 13-7-26* Time: 下午6:53* To change this template use File | Settings | File Templates.*/ @XmlRootElement // 標(biāo)注類名為XML根節(jié)點(diǎn) @XmlAccessorType(XmlAccessType.FIELD) // 表示將所有域作為XML節(jié)點(diǎn) public class User {private long id;private String username;private String password;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;} }?
Controller
package com.qunar.controller;import com.qunar.bean.User; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*;/*** Created with IntelliJ IDEA.* User: zhenwei.liu* Date: 13-7-26* Time: 下午6:54* To change this template use File | Settings | File Templates.*/ @Controller @RequestMapping("/users") public class UserController {// headers屬性標(biāo)明該方法只接受該Accept頭的請(qǐng)求@RequestMapping(value = "/{id}",method = RequestMethod.GET) // headers = {"Accept=text/xml, application/json, application/xml"})// @ResponseBody 表示返回的對(duì)象將轉(zhuǎn)換為客戶端Accept頭要求的表達(dá)形式// 假如客戶端請(qǐng)求頭沒包含任何形式,則假設(shè)客戶端可接受任何形式的返回// 返回的類型匹配方法默認(rèn)值是先查看URL擴(kuò)展名,沒有擴(kuò)展名則匹配Accept頭,否則匹配defaultContentType// @PathVariable 表示參數(shù)值來自URL,如果參數(shù)名與URL括號(hào)內(nèi)形參相同// 可以省略PathVariable內(nèi)的參數(shù)名public@ResponseBodyUser getUser(@PathVariable("id") long id) {User user = new User();user.setUsername("root");user.setPassword("root123");user.setId(id);return user;}// 設(shè)置RequestMapping的headers參數(shù)標(biāo)明請(qǐng)求體的內(nèi)容是json數(shù)據(jù)@RequestMapping(value = "/add", method = RequestMethod.POST,headers = "Content-Type=application/json")// @ResponseStatus表示響應(yīng)狀態(tài) NO_CONTENT表示無響應(yīng)內(nèi)容 @ResponseStatus(HttpStatus.NO_CONTENT)// 沒有配置ViewResolver的情況下@ResponseBody不能省略,否則404// @RequestBody表示將請(qǐng)求體的數(shù)據(jù)轉(zhuǎn)為user類public @ResponseBody void addUser(@RequestBody User user) {System.out.println(user.getId() + "|" + user.getUsername());} }?
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"><!-- 自動(dòng)注冊(cè)bean --><context:component-scan base-package="com.qunar"><context:include-filter type="regex" expression=".controller.*"/></context:component-scan><!-- 依賴注入注釋功能 --><context:annotation-config/><!-- 開啟MVC注釋功能 --><mvc:annotation-driven/><!-- 轉(zhuǎn)換器配置:只有配置好了轉(zhuǎn)換器才能進(jìn)行類與JSON和XML的轉(zhuǎn)換 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><!-- String 轉(zhuǎn)換器 --><ref bean="stringHttpMessageConverter"/><!-- JSON 轉(zhuǎn)換器 --><ref bean="jsonHttpMessageConverter"/><!-- XML 轉(zhuǎn)換器 --><ref bean="marshallingHttpMessageConverter"/></list></property></bean><bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/><bean id="jsonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/><bean id="marshallingHttpMessageConverter"class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"><constructor-arg ref="jaxbMarshaller"/><property name="supportedMediaTypes" value="application/xml" /></bean><bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"><!-- XML轉(zhuǎn)換器需要綁定需要轉(zhuǎn)換的類 --><property name="classesToBeBound"><list><value>com.qunar.bean.User</value></list></property></bean></beans>?
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.qunar"><context:include-filter type="regex" expression=".bean.*"/></context:component-scan></beans>?
?
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"version="2.5"><!-- 定義根目錄 --><context-param><param-name>webAppRootKey</param-name><param-value>restServer.root</param-value></context-param><listener><listener-class>org.springframework.web.util.WebAppRootListener</listener-class></listener><!-- 定義配置文件路徑 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring/context/applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 清理殘留在ServletContext的棄用參數(shù)的Listener --><listener><listener-class>org.springframework.web.context.ContextCleanupListener</listener-class></listener><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring/context/dispatcher-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>?
?
另外很重要的是把依賴包配好,否則各種ClassNotDefined
<!-- JSON 轉(zhuǎn)換器 --><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.12</version></dependency><!-- XML 轉(zhuǎn)換器 --><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>3.1.4.RELEASE</version></dependency>?
客戶端
import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate;/*** Created with IntelliJ IDEA.* User: zhenwei.liu* Date: 13-7-26* Time: 下午10:41* To change this template use File | Settings | File Templates.*/ public class Test {public static String urlGet = "http://localhost:8080/users/{id}";public static String urlPost = "http://localhost:8080/users/add";public static RestTemplate rt = new RestTemplate();// 從Rest接口獲取數(shù)據(jù)public static void getUser(long userId) {HttpHeaders headers = new HttpHeaders();// 設(shè)置Accept表示瀏覽器支持的MIME類型,此處意思是要返回的類型 headers.setAccept(MediaType.parseMediaTypes(MediaType.APPLICATION_XML_VALUE));HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);System.out.println(rt.exchange(urlGet,HttpMethod.GET,requestEntity,String.class,userId));System.out.println(rt.getForObject(urlGet, String.class, userId));}// 傳JSON數(shù)據(jù)到REST接口,自動(dòng)將JSON數(shù)據(jù)轉(zhuǎn)化成類public static void addUserByJson(String userJson) {HttpHeaders headers = new HttpHeaders();// 設(shè)置ContentType標(biāo)明數(shù)據(jù)是JSON數(shù)據(jù),否則報(bào)415(Unsupported Media Type)// 此處必須和REST接口的RequestMapping的ContentType對(duì)應(yīng) headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<Object> requestEntity = new HttpEntity<Object>(userJson, headers); // System.out.println(requestEntity.getBody().toString());rt.exchange(urlPost, HttpMethod.POST, requestEntity, null);}public static void main(String[] args) {getUser(1);addUserByJson("{\"id\":1,\"username\":\"root\",\"password\":\"root123\"}");} }輸出數(shù)據(jù)
<200 OK,<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user><id>1</id><username>root</username><password>root123</password></user>,{Server=[Apache-Coyote/1.1], Content-Type=[application/xml], Transfer-Encoding=[chunked], Date=[Sat, 27 Jul 2013 16:02:04 GMT]}>
{"id":1,"username":"root","password":"root123"}
轉(zhuǎn)載于:https://www.cnblogs.com/zemliu/p/3220517.html
總結(jié)
以上是生活随笔為你收集整理的Spring REST的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多异常处理
- 下一篇: Bellman 算法实现