1. 在Eclipse中新建一个Maven的Web项目,其中红色部分为要修改的文件
2. 在pom.xml中引入Jersey的依赖项:
<!-- 引入 Jersey的相关依赖项 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
3. 编写RESTful的资源类HelloWorldResource.java
package restful.res;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* The Java class will be hosted at the URI path "/helloworld"
*
* @author hp
*
*/
@Path("/helloworld")
public class HelloWorldResource {
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "text/plain"
@Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Jersey Hello World";
}
}
4. 在web.xml中添加对Jersey支持的Servlet:
<!-- 引入支持Jersey的Servlet容器 -->
<servlet>
<servlet-name>JerseyFirstServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<!-- 设置REST资源所在的包(可选) -->
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>restful.res</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>JerseyFirstServlet</servlet-name>
<url-pattern>/restful/*</url-pattern>
</servlet-mapping>
5. 用Maven打成war包并部署到Tomcat中进行测试
在浏览器中输入http://localhost:8080/JerseyFirst/restful/helloworld
测试成功!