Restful Jersey-1 入门例子

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- REST Services -->
    <servlet>
        <servlet-name>Rest_Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.zack.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Rest_Servlet</servlet-name>
        <!-- Redirect any calls to our jersey servlet -->
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

</beans>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>helloworld</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>helloworld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring 3 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.0.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.0.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.0.7.RELEASE</version>
    </dependency>

    <!-- Jersey -->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.13</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.13</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-servlet</artifactId>
        <version>1.13</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    
    <!--  json-->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    
    
    
    <!-- Jersey + Spring -->
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-spring</artifactId>
        <version>1.13</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
  </dependencies>
  <build>
    <finalName>helloworld</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version> 
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <encoding>UTF8</encoding> 
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

User.java

package com.zack.rest.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private String userName = "";
    private int age = 0;

    public User() {
        
    }

    public User(String userName,int age) {
        this.userName = userName;
        this.age = age;
    }
    
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "name:" + userName + " age:" + age;
    }
}

UserResource.java

package com.zack.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.zack.rest.domain.User;

@Component
@Scope("prototype")
@Path("/user")
public class UserResource {

    // 无参数返回json格式,如返回xml,将Produces参数修改为MediaType.APPLICATION_XML
    @GET
    @Path("/showUser")
    @Produces(MediaType.APPLICATION_JSON)
    public User showUser() {
        User user = new User();
        user.setUserName("sed");
        user.setAge(29);
        return user;
    }
    
    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> list() {
        List<User> userList = new ArrayList<User>();
        userList.add(new User("Lucy",29));
        userList.add(new User("Lily",30));
        return userList;
    }
    

    // @PathParam("id")获取URI中指定规则的参数
    @GET
    @Path("/show/{id}")
    @Produces(MediaType.TEXT_PLAIN)
    public String showByIdOfPath(@PathParam("id") String id) {
        return id;
    }
    
    // @QueryParam 用于获取GET请求中的查询参数
    @GET  
    @Path("/show")  
    @Produces(MediaType.TEXT_PLAIN)  
    public String showByIdOfQuery(@QueryParam("id") String id)  
    {  
        return id;  
    }
    
    // 输入参数为xml格式,输出为json格式。可以根据需要切换produces和consumes的类型
    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_JSON) // 指定响应所能接受的 MIME 类型
    @Produces(MediaType.APPLICATION_JSON) // 指定发送请求的 MIME 类型
    public User add(User user) {
        return user;
    }
    
    // BeanParam 当请求参数很多时,比如客户端提交一个修改用户的PUT请求,请求中包含很多项用户信息
    @PUT
    @Path("/update")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public User update(User user) {
        return user;
    }
    
    // @FormParam 从POST请求的表单参数中获取数据
    @POST
    @Path("/addFromForm")
    @Consumes("application/x-www-form-urlencoded")
    @Produces(MediaType.TEXT_PLAIN)
    public String addFromForm(@FormParam("username") String userName,@FormParam("age") int age) {
        User user = new User();
        user.setUserName(userName);
        user.setAge(age);
        return user.toString();
    }
    
    // 多参数传递
    @POST
    @Path("/multivalued")
    @Produces(MediaType.TEXT_PLAIN)
    public String multivalued(MultivaluedMap<String, String> formParams) {
        String result = "who:" + formParams.getFirst("who") + " ; what:" + formParams.getFirst("what");
        return formParams.toString();
    }    
    
    @DELETE
    @Path("delete/{id}")
    @Produces(MediaType.TEXT_PLAIN)
    public String delete(@PathParam("id") String id) {
        return "delete : " + id;
    }
}

UserResourceTest.java

package com.zack.rest;

import static org.junit.Assert.*;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.zack.rest.domain.User;

public class UserResourceTest {

    @BeforeClass
    public static void beforeClass() throws Exception{
        
    }
    
    @Before
    public void before() throws Exception {
        
    }

    @After
    public void after() throws Exception {
        
    }
    
    @AfterClass
    public static void afterClass() throws Exception{
        
    }
    
    private static WebResource getWebResource(String USER_URL) {
        Client client = Client.create(); // 创建一个 com.sun.jersey .api.client.Client类的实例
        WebResource webResource = client.resource(USER_URL); // 建了一个 WebResponse 对象
        return webResource;
    }
    
    @Ignore
    @Test
    public void testShowUser() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/showUser";
        System.out.println(getWebResource(USER_URL).get(String.class));
    }

    @Ignore
    @Test
    public void testList() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/list";
        System.out.println(getWebResource(USER_URL).get(String.class));
    }
    
    @Ignore
    @Test
    public void testShowByIdOfPath() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/show";
        System.out.println(getWebResource(USER_URL).path("123").get(String.class));
    }

    @Ignore
    @Test
    public void testShowByIdOfQuery() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/show";
        System.out.println(getWebResource(USER_URL).queryParam("id", "109").get(String.class));
    }

    @Ignore
    @Test
    public void testAdd() {
        User user = new User();
        user.setUserName("Jim");
        user.setAge(39);

        String USER_URL = "http://localhost:8080/helloworld/rest/user/add";
        String result = getWebResource(USER_URL).entity(user,MediaType.APPLICATION_JSON).post(String.class);
        System.out.println(result);
    }

    @Ignore
    @Test
    public void testAdd2() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/add";
        String userJson = "{"userName":"Jim","age":"6"}";
        String result = getWebResource(USER_URL).entity(userJson,MediaType.APPLICATION_JSON).post(String.class);
        System.out.println(result);
    }
    
    @Ignore
    @Test
    public void testUpdate() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/update";
        User user = new User();
        user.setUserName("Jim");
        user.setAge(39);
        System.out.println(getWebResource(USER_URL).entity(user,MediaType.APPLICATION_JSON).put(String.class)); 
    }
    
    @Ignore
    @Test
    public void testUpdate2() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/update";
        String json = "{"userName":"Jim","age":"6"}";
        System.out.println(getWebResource(USER_URL).entity(json,MediaType.APPLICATION_JSON).put(String.class)); 
    }

    @Ignore
    @Test
    public void testAddFromForm() {
        String USER_URL = "http://localhost:8080/helloworld/rest/user/addFromForm";
        Form form = new Form();
        form.add("username", "Jim");
        form.add("age",39);
        //ClientResponse 对象代表了一个客户端收到的 HTTP 响应。
        ClientResponse response = getWebResource(USER_URL).type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
        int status = response.getStatus();   //获取对应请求的 HTTP 状态码
        System.out.println("status:"+status);
        System.out.println(response.getEntity(String.class));
        
    }
    
    @Ignore
    @Test
    public void testMultivalued(){
        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        params.add("who", "Jim");
        params.add("what","do house work");
        params.add("how","use machine");
        params.add("where","Xue Lang");
        params.add("when","all day");

        String USER_URL = "http://localhost:8080/helloworld/rest/user/multivalued";
        String result = getWebResource(USER_URL).post(String.class,params);
        System.out.println(result);
    }
    
    @Ignore
    @Test
    public void testDelete(){
        String USER_URL = "http://localhost:8080/helloworld/rest/user/delete";
        String result = getWebResource(USER_URL).path("109").delete(String.class);
        System.out.println(result);
    }
}
原文地址:https://www.cnblogs.com/jingyunyb/p/4633077.html