请先看汇总篇「Web Service入门及实践」,学习前面的基础知识和例子再来看这篇!
使用Jersey实现REST web service入门之后其实发现还是很简单的,具体的实现步骤如下:
- 添加jar包依赖;
- 在web.xml中进行配置;
- 在代码中使用注解开发;
- 访问web service服务;
下面就是一个使用jersey 2打印“Hello World”的例子:
环境
- jersey版本:2.26
- JAX-RS版本:2.1
配置
Maven配置文件pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.howtodoinjava.jersey</groupId>
<artifactId>JerseyDemos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<jersey2.version>2.26</jersey2.version>
<jaxrs.version>2.1</jaxrs.version>
</properties>
<dependencies>
<!-- JAX-RS -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${jaxrs.version}</version>
</dependency>
<!-- Jersey 2.26 -->
<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>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>JerseyDemos</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml配置文件
<!--配置Jersey RESTful服务-->
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.cdsoft.epcp.rest.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>
注:如果你没有使用maven,那么只需要「下载」相应jar包,并添加到项目中就可以了。
java代码
代码如下:
package com.demo1.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
/**
* 打印HelloWord
* 浏览器地址:http://localhost:8080/jerseydemo/rest/helloworld
*/
@Path("/helloworld")
public class HelloWorldResource {
@GET
public String sayHelloWorld(){
return "Hello World! It's Jersey 2!";
}
}
开发浏览器访问地址:http://localhost:8080/jerseydemo/rest/helloworld
。
源码
参考文章: