Rest--入門

BtWangZhi發表於2017-11-02

1 簡單實現一個DEMO,由Tomcat容器啟動,將服務層暴露出來,類似RestFul,另外一段通過Http請求。
1.1 Maven依賴

<!-- 統一管理Spring的版本, spring.version為自定義的,其他的也可比如log.version -->
    <properties>
        <spring.version>4.3.10.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Part 1 -->
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.23.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-common</artifactId>
            <version>2.23.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.23.2</version>
        </dependency>

        <!-- Part 2:支援Json格式 ,否則會報: MessageBodyWriter not found for media type=application/json 
            ... 的錯誤 -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.23.2</version>
        </dependency>

        <!-- Part 3:支援複雜的Json格式翻譯,例如Map<K,E>,當然我們也可以使用Gson -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.23.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.1</version>
        </dependency>

        <!-- Part 4: 支援XML格式,否則會報MessageBodyWriter not found for media type=application/xml.... -->
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-xml-provider</artifactId>
            <version>2.8.1</version>
        </dependency>
    </dependencies>

1.2 Service層

@Path(value = "/")
public class UserServiceImpl{

    @GET
    @Path("login/{name}")
    public void login(@PathParam("name") String name) {
        System.out.println("run in name: " + name);
    }
}

1.3 web.xml

<servlet>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

1.4 Http訪問
依賴:

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
    </dependencies>

Http工具可以檢視:http://blog.csdn.net/btwangzhi/article/details/79029350
訪問:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        HttpClientUtil.doGet("http://localhost:8080/CXF/rest/login/dema");
    }