REST 之 Jersey REST framework

参阅姘文 http://www.ibm.com/developerworks/library/wa-aj-tomcat/

继完成了上一篇 REST 之 Spring 4 RESTful service 后,对于目前流行的REST框架乡进一步尝试,目前比较流行的有Jersey, Restlet, RestEasy等,我选择了一个据说最接近JSR-311的框架,而且它可以和Spring整合一起。

闲言少叙,直接上first hand的程序和实践

Steps:

1. 配置Eclipse 和 Maven, 请参见前文:环境搭建: Eclipse Luna, WTP, Maven and debug

2. Jersey项目采用了Maven来配置,现在新建一个maven项目,向导中选择web项目

3. 打开pom.xml,输入依赖包,并让eclipse自行下载。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.company</groupId>
  <artifactId>product</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>product Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <repositories>
	<repository> 
	    <id>people.apache.snapshots</id> 
	    <url> 
	        http://repository.apache.org/content/groups/snapshots-group/ 
	    </url> 
	    <releases> 
	        <enabled>false</enabled> 
	    </releases> 
	    <snapshots> 
	        <enabled>true</enabled> 
	    </snapshots> 
	</repository> 
  </repositories>
	 
  <pluginRepositories>
	<pluginRepository> 
	    <id>apache.snapshots</id> 
	    <name>Apache Snapshots</name> 
	    <url> 
	        http://repository.apache.org/content/groups/snapshots-group/ 
	    </url> 
	    <releases> 
	        <enabled>false</enabled> 
	    </releases> 
	    <snapshots> 
	        <enabled>true</enabled> 
	    </snapshots> 
	</pluginRepository>
  </pluginRepositories>
  
  
  <dependencies>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-grizzly2</artifactId>
        <version>1.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-spring</artifactId>
        <version>1.17.1</version>
    </dependency>
    <dependency>
	    <groupId>com.sun.jersey</groupId>
	    <artifactId>jersey-servlet</artifactId>
	    <version>1.17.1</version>
	</dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.17.1</version>
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>jsr311-api</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>product</finalName>
  </build>
</project>

这个pom下载完成后,应该在maven dependancies中看到jersey系列包,json,jaxb系列包。 另外如果我们用tomcat服务器,那我们可以手工加载external jar,选择tomcat目录中servlet-api.jar。

4. 添加servlet入口,以便 web container加载,web.xml如下:

<web-app>
  <display-name>Archetype Created Web Application</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.company.product</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>

5. 主接口如下:

/**
 * 
 */
package com.company.product;

import java.net.URI;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.xml.bind.JAXBElement;

import com.company.product.entity.Book;
import com.company.product.implementation.LibraryImp;
import com.company.product.interfaces.LibraryI;
import com.sun.jersey.api.Responses;
/**
 * @author zhuji06
 *
 */
@Path("/books")
public class HelloJersey {
	private LibraryI library = LibraryImp.getStore();
	
	@Context
	UriInfo uriInfo;
	
	@Context
	Request request;
	
	@GET
	@Path("/hello")
	@Produces(MediaType.APPLICATION_JSON)
	public String sayHello() {
		return "Hello Jersey";
	}
	
	@GET
	@Path("{bookId}")
	@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
	public Book getBook(@PathParam("bookId") Integer bookId){
		Book book = library.getBook(bookId);
		if(book == null)
			throw new WebApplicationException(Responses.notFound().build());
		return book;
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<Book> getBooks(){
		return library.getBooks();
	}
	
	@POST
	@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
	public Response createBook(Book book, @Context HttpServletResponse servletResponse){
		
		Integer id = library.addBook(book);
		URI uri = uriInfo.getAbsolutePathBuilder().path(String.valueOf(id)).build();
		return Response.created(uri).build();
	}
	
	@PUT
	public Response updateBook(Book book){
		
		library.putBook(book);
		return Response.noContent().build();
	}
	
	@DELETE
	@Path("{bookId}")
	public Response deleteBook(@PathParam("bookId") Integer bookId){
		library.deleteBook(bookId);
		return Response.noContent().build();
	}
}

6.  上面代码演示了PGPD (CRUD), 过程中使用了WebApplicationException来返回status code, 和exception description.

7.   忽略,请参考spring rest一文。

总结:

相比Spring Rest,Jersey严格的引入了JRS-311的标准定义,从行文配置也更加简单。同时对于RE转换也更加友好的支持,如list可以直接转换。不过,如果需要spring的其他东西的话,就不太满足了,比如mvc的支持等。就需要和spring集成在一起。

你可能感兴趣的:(REST 之 Jersey REST framework)