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);}}
建立一 rest Api
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)
返迴文本資訊
5. 編寫webcontent/web-inf/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/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>
6. 右鍵點擊項目,export to war檔案,到 tomcat7/webapps/目錄下
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