Spring REST


示例實現

1. 請求REST接口返回類轉換的JSON或XML數據

2. POST JSON數據到REST接口自動轉為類數據

服務端

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 // 標注類名為XML根節點
@XmlAccessorType(XmlAccessType.FIELD)   // 表示將所有域作為XML節點
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屬性標明該方法只接受該Accept頭的請求
    @RequestMapping(value = "/{id}",
            method = RequestMethod.GET)
//            headers = {"Accept=text/xml, application/json, application/xml"})
    // @ResponseBody 表示返回的對象將轉換為客戶端Accept頭要求的表達形式
    // 假如客戶端請求頭沒包含任何形式,則假設客戶端可接受任何形式的返回
    // 返回的類型匹配方法默認值是先查看URL擴展名,沒有擴展名則匹配Accept頭,否則匹配defaultContentType
    // @PathVariable 表示參數值來自URL,如果參數名與URL括號內形參相同
    // 可以省略PathVariable內的參數名
    public
    @ResponseBody
    User getUser(@PathVariable("id") long id) {
        User user = new User();
        user.setUsername("root");
        user.setPassword("root123");
        user.setId(id);
        return user;
    }

    // 設置RequestMapping的headers參數標明請求體的內容是json數據
    @RequestMapping(value = "/add", method = RequestMethod.POST,
            headers = "Content-Type=application/json")
    // @ResponseStatus表示響應狀態 NO_CONTENT表示無響應內容
    @ResponseStatus(HttpStatus.NO_CONTENT)
    // 沒有配置ViewResolver的情況下@ResponseBody不能省略,否則404
    // @RequestBody表示將請求體的數據轉為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">

    <!-- 自動注冊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/>

    <!-- 轉換器配置:只有配置好了轉換器才能進行類與JSON和XML的轉換 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- String 轉換器 -->
                <ref bean="stringHttpMessageConverter"/>
                <!-- JSON 轉換器 -->
                <ref bean="jsonHttpMessageConverter"/>
                <!-- XML 轉換器 -->
                <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轉換器需要綁定需要轉換的類 -->
        <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/javaee
          http://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的棄用參數的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 轉換器 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
        </dependency>

        <!-- XML 轉換器 -->
        <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接口獲取數據
    public static void getUser(long userId) {
        HttpHeaders headers = new HttpHeaders();
        // 設置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數據到REST接口,自動將JSON數據轉化成類
    public static void addUserByJson(String userJson) {
        HttpHeaders headers = new HttpHeaders();
        // 設置ContentType標明數據是JSON數據,否則報415(Unsupported Media Type)
        // 此處必須和REST接口的RequestMapping的ContentType對應
        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\"}");
    }
}

輸出數據

<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"}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM