使用Jax-rs 开发RESTfull API 入门
使用Jax-rs 开发RESTfull API 入门
本文使用 Jersey 2开发RESTfull API。Jersey 2 是 JAX-RS 接口的参考实现
使用到的工具
- Eclipse Neon
- Maven 3.3
- JDK 1.8
- Tomcat 8.0
依赖包
<properties>
<jersey2.version>2.25</jersey2.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- 以下两个库可对参数和返回值自动进行JSON与对象间转换-->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
</dependencies>
Servlet 配置
<servlet>
<servlet-name>jersey2-serlvet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>web.ws</param-value><!-- 服务类所在的包 -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey2-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Java 示例
package web.ws;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@Path("/first")
public class FirstRESTfull {
private static final Logger log = LoggerFactory.getLogger(FirstRESTfull.class);
@GET
@Path("/{userId}")
public String getParam(@PathParam(value = "userId") String userId) {
System.out.println(userId);
return userId;
}
}
将项目部署到Tomcat8.0,访问 http://localhost:8080/你的项目名/rest/first/sss
,浏览器页面将显示 sss
;