一、环境
jdk8 + Eclipse + Tomcat8.5 + jersey1.3
二、服务端
1、 新建Web项目,导入jersey等相应的jar包;
2、 新建User、UserDao、UserService这三个类,代码如下:
user类
package com.jersey.client;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User() {
}
public User(int id, String name, String profession) {
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
@XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao类
package com.jersey.client;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
private static List<User> users = new ArrayList<User>();
static {
users.add(new User(1, "zhangfei", "student"));
users.add(new User(2, "zhugeliang", "teacher"));
users.add(new User(3, "kongming", "teacher"));
users.add(new User(4, "likui", "student"));
}
public List<User> getAllUsers() {
return users;
}
public User getUserById(int id) {
if (users.isEmpty() || id <= 0) {
return null;
}
return users.get(id - 1);
}
public void deleteUserById(int id) {
if (users.isEmpty() || id <= 0) {
return;
}
users.remove(id - 1);
}
public void addUser(User user) {
if (user == null) {
return;
}
users.add(user);
}
}
服务器端Userservice类
package com.jersey.server;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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 com.alibaba.fastjson.JSON;
import com.jersey.client.User;
import com.jersey.client.UserDao;
// @Path here defines class level path. Identifies the URI path that
// a resource class will serve requests for.
@Path("UserInfoService")
public class UserService {
private UserDao userDao = new UserDao();
// add
@POST
@Path("/adduser")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<User> createUser(@QueryParam("id") String id, @QueryParam("name") String name) {
User user =new User(Integer.valueOf(id), name, null);
userDao.addUser(user);
return userDao.getAllUsers();
}
// delete
@DELETE
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<User> deleteUser(@PathParam("id") String id) {
userDao.deleteUserById(Integer.valueOf(id));
return userDao.getAllUsers();
}
// alter
@PUT
@Path("/updateUser")
@Consumes(MediaType.APPLICATION_XML)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<User> updateUser() {
User user = new User(6,"lily","student");
userDao.addUser(user);
return userDao.getAllUsers();
}
// query
@GET
@Path("/getall")
@Produces({ MediaType.APPLICATION_JSON })
public String getAllUsers() {
System.out.println(userDao.getAllUsers());
return JSON.toJSONString(userDao.getAllUsers());
}
// query
@GET
@Path("/name/{name}")
@Produces({MediaType.TEXT_XML })
public String getName(@PathParam("name") String name) {
System.out.println("get name");
return "<User>" + "<Name>" + name + "</Name>" + "</User>";
}
// query by id
@GET
@Path("getUserById/{id}")
@Produces({MediaType.TEXT_XML })
public User getUser(@PathParam("id") String id) {
return userDao.getUserById(Integer.valueOf(id));
}
}
三、客户端
代码如下:
package com.jersey.client;
import javax.ws.rs.core.MediaType;
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.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class UserInfoClient {
public static final String BASE_URI = "http://localhost:8080/jerseyTest";
public static final String PATH_AGE = "/UserInfoService/age/";
public static void main(String[] args) {
addUser();
queryByName();
queryUsers();
delUser(1);
queryUsers();
updateUser();
queryUsers();
queryById(3);
}
private static void queryByName() {
String name = "Lily";
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService/name/" + name);
System.out.println("按姓名查找 \n"
+ getClientResponse(nameResource));
System.out.println("Response \n" + getResponse(nameResource) + "\n\n");
}
private static void queryById(int id) {
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService/getUserById").path(String.valueOf(id));
System.out.println("按ID查找\n"
+ getClientResponse(nameResource));
System.out.println("Response \n" + getResponse(nameResource) + "\n\n");
}
private static void updateUser() {
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService").path("updateUser");
System.out.println("更新用户\n"
+ nameResource.accept(MediaType.TEXT_XML,MediaType.APPLICATION_JSON).put(ClientResponse.class));
System.out.println("Response \n" + nameResource.accept(MediaType.TEXT_XML,MediaType.APPLICATION_JSON).put(Object.class) + "\n\n");
}
private static void delUser(int id) {
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService").path(String.valueOf(id));
System.out.println("删除用户:\n"
+ nameResource.accept(MediaType.TEXT_XML,MediaType.APPLICATION_JSON).delete(ClientResponse.class));
System.out.println("Response \n" + nameResource.accept(MediaType.APPLICATION_JSON,MediaType.TEXT_XML).delete(Object.class) + "\n\n");
}
private static void queryUsers() {
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService/getall");
System.out.println("查询所有用户:\n"
+ getClientResponse(nameResource));
System.out.println("Response \n" + nameResource.accept(MediaType.APPLICATION_JSON,MediaType.TEXT_XML).get(String.class) + "\n\n");
}
private static void addUser() {
WebResource resource = getResource();
WebResource nameResource = resource.path("rest").path("/UserInfoService/adduser").queryParam("id", "5").queryParam("name", "nn");
System.out.println("增加用户: \n"
+ nameResource.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML).post(ClientResponse.class));
System.out.println("Response \n" + nameResource.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_XML).post(Object.class) + "\n\n");
}
private static String getClientResponse(WebResource resource) {
return resource.accept(MediaType.APPLICATION_JSON,MediaType.TEXT_XML).get(ClientResponse.class)
.toString();
}
public static String getResponse(WebResource resource) {
return resource.accept(MediaType.TEXT_XML).get(String.class);
}
private static WebResource getResource() {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(BASE_URI);
return resource;
}
}
四、web.xml
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>jerseyTest</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.jersey.server</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
五、pom
<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.jersey</groupId>
<artifactId>jerseyTest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>jerseyTest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
</dependencies>
<build>
<finalName>jerseyTest</finalName>
</build>
</project>