基於Jersey框架搭建Restful Java Web Service的基本步驟
本文由Markdown語法編輯器編輯完成。
1. Restful Web Service
2. Restful的基本框架
3. 基於Jersey框架搭建Restful Web Service的基本步驟
Jersey框架不僅實現了JAX-RS規範,還提供了自有API以擴充套件JAX-RS, 提供了更多的特性和工具進一步簡化Restful Web Service及其客戶端開發。
一個典型的Jersey RESTful Web Services就是一個簡單的java類+Jersey提供的註解,例如:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
@Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
}
@Path(“myresource”)表示MyResource類處理路徑為/myresource的請求,@GET表示請求是GET請求,@Produces(MediaType.TEXT_PLAIN)表示服務返回的資料型別是簡單文字型別。
按照上面的寫法如果把RESTful的服務搭建在本地的Tomcat伺服器上的話,那麼向該服務傳送Get請求的時候的URL應該為:
localhost:8080/myresource。
3.1 專案原始碼載入Eclipse:
從連結https://www.ibm.com/developerworks/cn/web/wa-aj-tomcat/下載專案的原始碼,並且載入Eclipse工程中,可以看到專案的組織結構如下圖所示:
(圖中紅色線框包含的lib,都是根據相關類的需求,從jar下載網站下載後載入進工程的lib庫中的)
專案的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>Jersey</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
3.2 多種客戶端向Restful服務請求資源例項:
將該Java web專案載入Tomcat 8.0中,啟動服務後,即可根據以下的訪問地址,向該Restful Web Service發起請求。
發起請求可以有多種方式發起:
(1)直接在Chrome等瀏覽器的位址列中輸入Restful資源的URL,即可預設向Restful伺服器發起Get請求;
(2)用SoapUI或Google的外掛Postman,可以模擬由客戶端向Restful伺服器發起Get, Put, Post, Delete等請求。
3.2.1 Chrome瀏覽器請求Restful資源
以下是在Chrome瀏覽器中通過直接輸入Resources的URL後,返回的Json資源:
輸入地址為:localhost:8080/ProjectName/rest/hello
ProjectName = “Jersey.Sample.Contact.Src”.
輸入地址為: localhost:8080/ProjectName/rest/contacts