1. Eclipse新建一个dynamic web project
2. 下载Jersey库文件,https://jersey.java.net/,将其中所有jar复制到webcontent/web-inf/lib目录下 (当前最新版本是jaxrs-ri-2.9.zip)
3. 保证当前使用的是JRE7/JDK1.7 以兼容Jersey类库
4. 编写 HelloWorld Web Service
package cn.com.chaser.restapi; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.server.ResourceConfig; public class RestApplication extends ResourceConfig { public RestApplication() { packages("cn.com.chaser.restapi"); register(LoggingFilter.class); } }
package cn.com.chaser.restapi; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/restService") public class RestService { @GET @Path("/getInfo") @Produces(MediaType.TEXT_PLAIN) public String getWebServiceInfo() { return "Hello,RESTful web service!"; } @GET @Path("/{parameter}") public Response respondMessage(@PathParam("parameter") String parameter, @DefaultValue("Nothing to say") @QueryParam("value") String value) { String out = "Hello from " + parameter + ":" + value; return Response.status(200).entity(out).build(); } }
@GET:表示该接口接受GET方法
@Path: 定义访问路径
@Produces(MediaType.TEXT_PLAIN)返回文本信息
<?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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>RestService</display-name> <servlet> <servlet-name>mobile</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>cn.com.chaser.restapi.RestApplication</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mobile</servlet-name> <url-pattern>/rest/*</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>
7. 启动tomcat7进行测试
a) http://localhost:8080/RestService/rest/restService/getInfo
显示:
Hello,RESTful web service!
b) http://localhost:8080/RestService/rest/restService/getInfow
显示:
Hello from getInfow:Nothing to say
c) http://localhost:8080/RestService/rest/restService/wwwsw?value=24
返回:
Hello from wwwsw:24
参考:
1. http://www.vogella.com/tutorials/REST/article.html
2. https://jersey.java.net/nonav/documentation/latest/user-guide.html