实践是检验真理的唯一标准,上篇文章主要介绍了RESTful service resources思想创建服务,这篇我们用其思想和Jersey框架创建一个项目(本文是针对在eclipse中的项目来进行的,maven和ant developers的用户搭建环境可参照https://jersey.java.net/nonav/documentation/latest/jax-rs.html网页):
有关jersey的介绍,上章已经介绍过了,这里再重复一下:Jersey是由SUN提供的JAX-RS实现参考,对JAX-RS支持的最为充分和快速,基本上所有的JAX-RS的新特性都会在Jersey里第一个体现出来。
废话不说,直接动手:
第一步,create project:
eclipse_j2ee中file->new project->dynamic web project,命名为RestDemo.
第二步,添加库文件
- grizzly-http-server.jar,
- grizzly-http.jar,
- grizzly-framework.jar,
- jersey-server.jar,
- jersey-grizzly2.jar,
- jersey-core.jar,
- jersey-bundle.jar
- jsr311-api.jar,
- asm.jar
第三步,在你的工程中创建资源类:
package com.frand.RestDemo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
//The Java class will be hosted at the URI path "/helloworld"
@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 "Hello World";
}
}
第四步,在你的项目中创建资源管理类:
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import javax.ws.rs.ApplicationPath;
import com.frand.RestDemo.HelloWorldResource;
/**
*
* @author frand
*/
public class Main extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register root resource
classes.add(HelloWorldResource.class);
return classes;
}
}
第五步,在web.xml文件中配置环境参数:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RestDemo</display-name>
<servlet>
<servlet-name>com.frand.Main</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.frand.Main</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>com.frand.Main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
第六步,右击项目,run as->run on server;就会在内置浏览器中看到Hello World两个单词。