##一、下載Jersey相關jar包,本示例用的版本是Jersey 2.22.1 ##二、eclipse新建dynamic web 項目,將Jersey相關包複製到WebContext/web-info/lib下,並添加項目對這些包的引用 ##三、編寫入口類RestApplicationhtml
package com.newbsoft.restful; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.server.ResourceConfig; public class RestApplication extends ResourceConfig { public RestApplication() { packages("com.newbsoft.restful"); register(LoggingFilter.class); } }
##四、編寫WebService 資源類(在Restful中,對客戶端而已,全部操做請求都是申請資源)java
package com.newbsoft.restful.spi; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("hello") public class HelloSpi { @GET @Produces(MediaType.TEXT_PLAIN) public String resHi(){ return "hi~ it's me!"; } }
##五、配置web.xml,啓動Tomcat服務器web
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>RestfulWS</display-name> <servlet> <servlet-name>RestWS</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.newbsoft.restful.RestApplication</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>RestWS</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>
##六、最後一步,測試 瀏覽器中輸入http://localhost:8080/RestfulServer/rest/hello,便可看到頁面返回 「hi~ it's me!」 url說明:RestfulServer是項目部署目錄名稱瀏覽器