前言
在短信平台一期工作中,为便于移动平台的开发,使用了Java Jersey框架开发RESTFul风格的Web Service接口。在使用的过程中发现了一些问题并积累了一些项目经验,做了一下总结,便于个人成长,同时也希望对有需要的同仁有好的借鉴和帮助。
简介
Jersey是JAX-RS(JSR311)开源参考实现用于构建 RESTful Web service,它包含三个部分:
-
核心服务器(Core Server) :通过提供JSR 311中标准化的注释和API标准化,可以用直观的方式开发RESTful Web服务。
-
核心客户端(Core Client) :Jersey客户端API能够帮助开发者与RESTful服务轻松通信;
-
集成(Integration) :Jersey还提供可以轻松继承Spring、Guice、Apache Abdera的库。
在本次开发中使用Jersey2.0,并且仅使用了核心服务器。
设置Jersey环境
在pom.xml文件增加依赖包
<!--jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<!--JAXB API -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- Json支持 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
引入Jar文件方式
从Jersey开发包中将以下库复制的WEB-INF下的库目录:
-
服务器:jersey-server.jar 、jersey-container-servlet-core.jar、jersey-container-servlet.jar、javax.ws.rs-api-2.0.jar
-
客户端:jersey-client.jar
-
common:jersey-common.jar
-
json支持:在Jersey2.0中需要使用 Jackson1.9 才能支持json。
Hello World
以下将展示一个Hello World
第一步: 编写一个名为HelloService服务,它接受Http Get请求并响应“Hello Jersey”
package com.duotun.webapi;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("hello")
public class HelloService {
@GET
@Produces(MediaType.APPLICATION_XML)
public String hi() {
return "hello jersey";
}
}
第二步:在web.xml文件中定义servelt调度程序,目的是将所有REST请求发送到Jersey容器。除了声明Jersey Servlet外,还需定义一个初始化参数,指定JAX-RS application。请注意,要与springMVC集成这里用的是filter,不是servlet标签。
<!-- jersey api 监听器 -->
<filter>
<filter-name>JerseyServletContainer</filter-name>
<filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.duotun.webapi</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>JerseyServletContainer</filter-name>
<url-pattern>/webapi/*</url-pattern>
</filter-mapping>
简单解释一下这段代码:
1,注意类是放在com.duotun.webapi包中,而这个包是我们jersey.config.server.provider.packages参数中配置的包的子包,即该类是能够被扫描到的;
2,在类上面添加了@Path("hello"),代表资源根路径为hello,类似于SpringMVC中在类上面添加@RequestMapping("hello");
3,方法hi上面添加了两个标签,@GET标签代表该方法接受GET类型请求,类似于SpringMVC中的@GetMapping标签;
4,@Produces标签代表该方法的响应MIME类型为text/plain,类似于@RequestMapping中的produces属性;
5,该方法返回String,这个String值Jersey会自动按照text/plain格式输出。
启动tomcat,请求/webapi/hello,得到正确的响应