前言
此篇文章介紹如何使用Jersey架設RESTful web service,使用到的工具如下1. Eclipse Luna
2. Tomcat 7
3. Jersey 2.11
為避免對Maven或Gradle不熟悉的人感到疑惑,因此此篇文章只針對如何使用Jersey 2架設RESTful service,不使用Maven或Gradle進行管理
架設步驟
1. 開啟Eclipse2. 建立新的專案File -> New -> Dynamic Web Project
3. 輸入專案名稱JerseySample並選擇Apache Tomcat v7.0作為Target runtime,記得要把Generate web.xml deployment descriptor打勾
4. 將jersey官網下載的jaxrs-ri-2.11.zip解壓縮,接著把所有的jar檔複製到jerseySample/WebContent/WEB-INF/lib下
5. 重新整理JerseySample專案確保lib都有正常載入
6. 修改web.xml讓Tomcat可以正確載入Jersey相關資源
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JerseySample</display-name> <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> <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>org.sample.test</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> </web-app>
參數說明
i. servlet-class
Jersey 1的servlet-class為
com.sun.jersey.spi.container.servlet.ServletContainer
而Jersey 2的servlet-class必須改成(畢竟Sun已經R.I.P.了QAQ........)
org.glassfish.jersey.servlet.ServletContainer
ii. jersey.config.server.provider.packages
Jersey掃描的packet路徑,resource的java檔要放在此package下
iii. url-pattern
Resource對應的URL位置,client端必須要照此參數設定才能呼叫到對應的resource
7. 建立package: org.sample.test
8. 建立resource的java檔案: Hello.java
9. 加入以下的程式碼至Hello.java
package test; 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 Hello { // This method is called if TEXT_PLAIN is request @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey"; } // This method is called if XML is request @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "" + "Hello Jersey" + " "; } // This method is called if HTML is request @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + "Hello Jersey" + "</h1></body></html></pre>" + " "; } }
10. 將專案在Tomcat上跑起來,並使用瀏覽器檢查http://localhost:8080/JerseySample/api/hello是否正確
11. 使用RESTful client工具檢查xml的request是否能正常使用。只要送出的request包含Accept: text/xml檔頭,Jersey就會自動切換到回傳sayXMLHello函式結果
參考資料
1. REST with Java (JAX-RS) using Jersey - Tutorial (適用Jersey 1)
2. Jersey 2.5 + Maven = easy REST web services