使用Jersey快速實現rest風格的webservice
阿新 • • 發佈:2019-01-04
JAVA EE6 引入的一個新技術:JAX-RS(Java API for RESTful Web Services)。這是一個Java 程式語言的應用程式介面,支援按照表述性狀態轉移(REST)架構風格建立Web服務。它有好幾種實現方式,而Jersey是其參考實現方式。Jersey的詳細介紹請參考:Jersey官網。
說明:Jsersey預設使用maven框架,這裡假設你已經安裝好maven及tomcat服務。
一 新建測試專案
這一步將新建一個JavaEE Web Application,可以打包成war包並部署到伺服器上。 執行下面的mvn命令新建工程。其中groupId,mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp \ -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \ -DgroupId=com.example -DartifactId=simple-service-webapp -Dpackage=com.example \ -DarchetypeVersion=2.22.2
artifactId
,package
可以更換。
理論上也可以用eclipse建立這個工程,但本人在eclipse的maven模板中找不到jersey-quick-webapp,所以還是使用的命令建立。
建立好後預設的工程目錄是這樣的:
如上圖,工程模板非常簡單,只有如上四個檔案,不需要任何修改便能測試。其中MyResouce.java程式碼如下:
package com.example; 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和@GET指明瞭使用get方法訪問子路徑myresource便會返回"Got it!"。 web.xml中還配置了servlet-mapping:
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
這樣在本機部署好專案後,訪問localhost:8080/simple-service-webapp/webapi/myresource二 測試
這一步可以在eclipse上完成。但這裡介紹如何打包成war並部署到tomcat。 在工程的pom.xml目錄執行mvn clean package
這樣會在該目錄下生成一個target資料夾,將target下面的simple-service-webapp.war拷貝到tomcat的webapps下面。 啟動tomcat服務:
startup.bat
啟動成功後再瀏覽器中訪問:
測試OK!
三 使用Json
官方文件中介紹了好幾種方法,這裡介紹基於JAXB的MOXy方法。這個方法使用起來也很簡單。只需要把pom.xml中相應的註釋去掉即可<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->
去掉註釋後新增測試類User.java。程式碼如下:
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.*;
@Path("user/{username}")
@XmlRootElement
public class User {
public String name;
public int age;
public User(){}
public User(String name, int age){
this.name = name;
this.age = age;
}
@GET
@Produces("application/json")
public User getUser(@PathParam("username") String userName){
return new User(userName, 28);
}
}
完成後按照第二部重新部署,在瀏覽器中測試如下: 後記:官方文件中還詳細介紹了HTTP的POST,PUT,DELETE及URL中的引數處理,還有更多關於Jersey的知識。欲瞭解更多請參考官網。