本文演示环境为eclipse + Maven插件 + Jersey framework。本文只关注Jersey的使用,所以只使用类中定义的静态数据做演示。请在使用时修改我的代码。如果你的eclipse中没有安装 Maven插件,请关注我的博客,我马上就会推出Maven+eclipse的开发教程。
1. 在eclipse中创建Maven项目
2.单击"Next"
3. 选择Maven项目类型为"maven-archetype-webapp"
4. 输入项目相关的Maven设置
5. 分别创建src/main下java文件夹以及src下test文件夹
6. 设置src/main/java和src/test/java为source folder
7. 最终设置结果如下:
8. 修改pom.xml,添加Maven相应依赖库
<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>net.jianxi.tutorials.jerseyws</groupId> <artifactId>jerseywstest</artifactId> <packaging>war</packaging> <version>1.0</version> <name>jerseywstest 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>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> </dependencies> <build> <finalName>jerseywstest</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <configuration> <warFile>target/jerseywstest.war</warFile> </configuration> </plugin> </plugins> </build></project>
9. 添加基本POJO类Student:
1 package net.jianxi.tutorials.jerseyws.metadata; 2 3 ?import javax.xml.bind.annotation.XmlRootElement; 4 5 @XmlRootElement 6 ?public class Student { 7 private int id; 8 private String name; 9 private String dept;10 11 public int getId() {12 return id;13 }14 15 public Student() {16 }17 18 public Student(int id, String name, String dept) {19 super();20 this.id = id;21 this.name = name;22 this.dept = dept;23 }24 public void setId(int id) {25 this.id = id;26 }27 public String getName() {28 return name;29 }30 public void setName(String name) {31 this.name = name;32 }33 public String getDept() {34 return dept;35 }36 public void setDept(String dept) {37 this.dept = dept;38 }39 40 }41 ?
10. 添加一个REST web服务实现类RestWsDemo:
1 package net.jianxi.tutorials.jerseyws; 2 3 ?import java.util.ArrayList; 4 ?import java.util.HashMap; 5 ?import java.util.List; 6 ?import java.util.Map; 7 8 ?import javax.ws.rs.DELETE; 9 ?import javax.ws.rs.FormParam;10 ?import javax.ws.rs.GET;11 ?import javax.ws.rs.POST;12 ?import javax.ws.rs.PUT;13 import javax.ws.rs.Path;14 import javax.ws.rs.PathParam;15 import javax.ws.rs.Produces;16 import javax.ws.rs.QueryParam;17 import javax.ws.rs.core.MediaType;18 19 import net.jianxi.tutorials.jerseyws.metadata.Student;20 21 import org.apache.log4j.Logger;22 23 24 @Path("/students")25 public class RestWsDemo {26 private static Logger logger = Logger.getLogger(RestWsDemo.class);27 private static int index = 1;28 private static Map<Integer,Student> studentList = new HashMap<Integer, Student>();29 30 public RestWsDemo() {31 if(studentList.size()==0) {32 studentList.put(index, new Student(index++, "Frank", "CS"));33 studentList.put(index, new Student(index++, "Jersey", "Math"));34 }35 }36 37 @GET38 @Path("{studentid}")39 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})40 public Student getMetadata(@PathParam("studentid") int studentid) {41 if(studentList.containsKey(studentid))42 return studentList.get(studentid);43 else44 return new Student(0, "Nil", "Nil");45 }46 47 @GET48 @Path("list")49 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})50 public List<Student> getAllStudents() {51 List<Student> students = new ArrayList<Student>();52 students.addAll(studentList.values());53 return students;54 }55 56 @POST57 @Path("add")58 @Produces("text/plain")59 public String addStudent(@FormParam("name") String name,60 @FormParam("dept") String dept) {61 studentList.put(index, new Student(index++, name, dept));62 return String.valueOf(index-1);63 }64 65 @DELETE66 @Path("delete/{studentid}")67 @Produces("text/plain")68 public String removeStudent(@PathParam("studentid") int studentid) {69 logger.info("Receieving quest for deleting student: " + studentid);70 71 Student removed = studentList.remove(studentid);72 if(removed==null) return "failed!";73 else return "true";74 } 75 76 @PUT77 @Path("put")78 @Produces("text/plain")79 public String putStudent(@QueryParam("studentid") int studentid,80 @QueryParam("name") String name,81 @QueryParam("dept") String dept82 ) {83 logger.info("Receieving quest for putting student: " + studentid);84 if(!studentList.containsKey(studentid))85 return "failed!";86 else87 studentList.put(studentid, new Student(studentid, name, dept));88 89 return String.valueOf(studentid);90 } 91 }92
11. 修改src/main/webapp/WEB-INF/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> <servlet> <servlet-name>jerseyws</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name> <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>net.jianxi.tutorials.jerseyws</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jerseyws</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
12. 运行Maven package任务,构建war文件,部署war应用到你的Web服务器。
13. 测试
我马上就会推出如何用SoapUI工具测试Jersey Web服务的教程。这里这介绍简单的测试方法。
13.1) 对于GET,可以直接通过浏览器进行测试,在浏览器中直接输入:http://localhost:8080/jerseywstest/rest/students/list, 你应该看到返回的XML数据:
输入:http://localhost:8080/jerseywstest/rest/students/1则会返回一个学生的信息。<students> <student> <dept>CS</dept> <id>1</id> <name>Frank</name> </student> <student> <dept>Math</dept> <id>2</id> <name>Jersey</name> </student></students>
13.2) 测试POST方法。
添加一个testpost.htm文件
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body> <form action="/jerseywstest/rest/students/add" method="post"> <input type="text" id="name" name="name"/><br/> <input type="text" id="dept" name="dept"/><br/> <input type= "submit"/> </form></body></html>
?提交后你在用list方法就可以看到数据的变化。
13.3) PUT和DELETE方法的测试
添加一个Junit测试类
1 package net.jianxi.tutorials.jerseyws; 2 3 4 ?import javax.ws.rs.core.MultivaluedMap; 5 6 ?import org.junit.Before; 7 ?import org.junit.BeforeClass; 8 ?import org.junit.Test; 9 10 ?import com.sun.jersey.api.client.Client;11 ?import com.sun.jersey.api.client.ClientResponse;12 ?import com.sun.jersey.api.client.WebResource;13 ?import com.sun.jersey.core.util.MultivaluedMapImpl;14 15 ?public class RestWsDemoTest {16 private String url = "http://localhost:8080/jerseywstest/rest/students";17 18 @Test19 public void testDelete() {20 Client client = Client.create();21 WebResource webResource = client.resource(url + "/delete/1");22 ClientResponse response = webResource.delete(ClientResponse.class);23 24 System.out.println("Response for delete request: " + response.getStatus());25 }26 27 @Test28 public void testPut() {29 Client client = Client.create();30 WebResource webResource = client.resource(url + "/put");31 MultivaluedMap queryParams = new MultivaluedMapImpl();32 queryParams.add("studentid", "2");33 queryParams.add("name", "nametest");34 queryParams.add("dept", "depttest");35 ClientResponse response = webResource.queryParams(queryParams).put(ClientResponse.class, "foo:test");36 System.out.println("Response for put request: " + response.getStatus());37 }38 }39 ?