---
title: "Restful Web Service 介绍及Jersey实现"
author: "zchiml"
date: "2012-11-26T10:51:21Z"
tags: []
categories: ["企业架构"]
slug: "restful-web-service-jersey"
draft: false
lastmod: "2012-12-27T17:40:45Z"
id: 1733729
url: "https://zchiml.iteye.com/blog/1733729"
---

**REST**

 

2000 年由 Roy Fielding 在博士论文中提出，他是 HTTP 规范 1.0 和 1.1 版的首席作者之一。

 

REST 中最重要的概念是*资源（resources）* ，使用全球 ID（通常使用 URI）标识。客户端应用程序使用 HTTP 方法（`GET/ POST/ PUT/ DELETE` ）操作资源或资源集。RESTful Web 服务是使用 HTTP 和 REST 原理实现的 Web 服务。通常，RESTful Web 服务应该定义以下方面：

- Web 服务的基/根 URI，比如 http://host/&lt;appcontext&gt;/resources。
- 支持 MIME 类型的响应数据，包括 JSON/XML/ATOM 等等。
- 服务支持的操作集合（例如 `POST、GET、PUT` 或 `DELETE)`

如下表所示：

**方法/资源**   资源集合， URI 如：  
http://host/&lt;appctx&gt;/resources    成员资源，URI 如：  
http://host/&lt;appctx&gt;/resources/1234  **GET** 列出资源集合的所有成员 检索标识为 1234 的资源的表示形式。 PUT 使用一个集合更新（替换）另一个集合。 更新标记为 1234 的数字资源。 POST 在集合中创建数字资源 在下面创建一个子资源。 DELETE 删除整个资源集合。 删除标记为 1234 的数字资源。

 

 

**JSR－311  Java API for RESTful Web Services (JAX-RS) 1.0 and 1.1**

      JAX-RS是将在JavaEE 6引起的一种新技术。 JAX-RS即Java API for RESTful Web Services，是一个Java 编程语言的[应用程序接口](http://baike.baidu.com/view/592964.htm) ，支持按照表述性状态转移（REST）架构风格创建Web服务。JAX-RS使用了Java SE5引入的Java标注来简化Web服务的客户端和[服务端](http://baike.baidu.com/view/1087294.htm) 的开发和部署。包括：

 

- @Path，标注资源类或者方法的相对路径
- @GET，@PUT，@POST，@DELETE，标注方法是HTTP请求的类型。
- @Produces，标注返回的MIME媒体类型
- @Consumes，标注可接受请求的MIME媒体类型
- @PathParam，@QueryParam，@HeaderParam，@CookieParam，@MatrixParam，@FormParam,分别标注方法的参数来自于HTTP请求的不同位置，例如@PathParam来自于URL的路径，@QueryParam来自于URL的查询参数，@HeaderParam来自于HTTP请求的头信息，@CookieParam来自于HTTP请求的Cookie。

 

**Jersey 实现**

 

Jersey 是 JAX-RS 的参考实现，它包含三个主要部分。

- 核心服务器（Core Server）：通过提供 JSR 311 中标准化的注释和 API 标准化，您可以用直观的方式开发 RESTful Web 服务。
- 核心客户端（Core Client）：Jersey 客户端 API 帮助您与 REST 服务轻松通信。
- 集成（Integration）：Jersey 还提供可以轻松集成 Spring、Guice、Apache Abdera 的库。

 

**用微账户的查询接口作一个例子**

 

```
@Path("/accinfo")
public class AccountInfoResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	
	/*
	 * Get all accounts info
	 */
	@GET
	@Path("all")
	@Produces(MediaType.APPLICATION_XML)
	public List<AccountInfo> getAllaccounts() throws UnsupportedEncodingException{
		List<AccountInfo> retList = new ArrayList<AccountInfo>();
		EntityManager em = EntityManagerHelper.getEntityManager();
		MaaccdtapManager mm = new MaaccdtapManager(em);
		List<Maaccdtap> mList = mm.getAllAccounts();
		AccountInfo ai = null;
		AccountAdapter ad = new AccountAdapter();
		
		for(Maaccdtap m : mList){			
			ai = ad.getAccountInfo(m);
			retList.add(ai);
		}
		
		EntityManagerHelper.closeEntityManager();
		
		return retList;
	}	
	
	/*
	 * Get account info by mbrseq id
	 */
	@GET
	@Path("{accountid}")
	@Produces(MediaType.APPLICATION_XML)
	public AccountInfo getAccountBySid(@PathParam("accountid") String accountid) 
			throws UnsupportedEncodingException{
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		MaaccdtapManager mm = new MaaccdtapManager(em);
		Maaccdtap mp = mm.getAccountBySid(accountid);
		AccountInfo ai = null;
		
		if(null != mp){
			AccountAdapter ad = new AccountAdapter();
			ai = ad.getAccountInfo(mp);
		}
		
		EntityManagerHelper.closeEntityManager();
		
		return ai;
	}

        @POST
	@Path("change")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public void responseAccountChange(
			@FormParam(value = "id") String id,
			@FormParam(value = "name") String name,
			@Context HttpServletResponse servletResponse) throws IOException{
		
	
	System.out.println("Reveiced change parameters from UI:");
	System.out.println("ID is " + id);
	System.out.println("Name is " + name);
	
	URI newUrl = uriInfo.getAbsolutePathBuilder().path(id).build();
	System.out.println(newUrl.toString());
	
	Response.created(newUrl).build();
	//ServletOutputStream os = servletResponse.getOutputStream();
	PrintWriter pw = servletResponse.getWriter();
	pw.write("The change request has been sent to backend and id is " + id);
	pw.flush();
	}
 }
```

用下面的URL即可访问相应的账户信息（即Resource）

   http://ip:port/MicroAcc/rest/accinfo/{mbrseq}       
   http://ip:port/MicroAcc/rest/accinfo/al l

@Produces(MediaType.APPLICATION\_JSON)则可以产生Json的输出。

 

@POST注释会接收http post request, 将Web表单里的action指向POST的地址，例如：

   http://ip:port/MicroAcc/rest/accinfo/change

被注释的方法即可收到表单的内容。

**Jersey配置：**

Jersey 1.2 以后的版本和一些Update的维护版本只支持Java SE 6, 在选择版本和相应服务器时需要注意。

 

从 Jersey 开发包中以下的库为必须：

- 核心服务器：jersey-core.jar，jersey-server.jar，jsr311-api.jar，asm.jar
- JAXB 支持：jaxb-impl.jar，jaxb-api.jar，activation.jar，stax-api.jar，wstx-asl.jar
- JSON 支持：jersey-json.jar

 

**Web.xml:**

 

```
<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>sh.cmbchina.pension.resources</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>
```

 这样，所有在包sh.cmbchina.pension.resources下面的resource类都会被注册为Restful url的响应处理类。