本系列的Jersey主要是快速介紹如何使用Jersey建立RESTful service,記錄自己在學習過程中使用或遇到的問題。在最開始會使用輕量級的Grizzly HTTP server發布RESTful service.
1. 使用Mave創建工程
在pom.xml文件中加入如下以來的jar, jersey-server是實現service side的RESTful, jersey-grzzly2是用來發布RESTful的輕量級的server。
1 <dependencies> 2 <dependency> 3 <groupId>com.sun.jersey</groupId> 4 <artifactId>jersey-server</artifactId> 5 <version>1.17.1</version> 6 </dependency> 7 <dependency> 8 <groupId>com.sun.jersey</groupId> 9 <artifactId>jersey-grizzly2</artifactId> 10 <version>1.17.1</version> 11 </dependency> 12 </dependencies>
2. 開始Server side的開發
1) 使用Annotation編寫Root Resource Classes, Root resource Classess實際是一個POJO對象,通過Annotation將其中的方法發布為RESTful service.
1 package com.study.jersey.server; 2 3 import javax.ws.rs.GET; 4 import javax.ws.rs.Path; 5 import javax.ws.rs.Produces; 6 7 @Path("helloworld") 8 public class HelloWorldResource { 9 10 @GET 11 @Produces(MediaType.TEXT_PLAIN)
12 public String sayHelloWorld(){ 13 return "Hello World!"; 14 } 15 }
@Path:
@Path注釋是一個相對的URI路徑,在上面的代碼中,Java class的資源標識可以通過UIR路徑/helloworld表示。在此類中因為只有一個方法,所以可以通過http://<ip>:<port>/hellowrld訪問sayHelloworld方法。
@GET:
該注釋是定義資源通過Http的Get請求方式可以訪問該資源,相應的還有Pot, Put等。
@Produces:
該注釋是用於指定被消費的資源返回到客戶端所使用的MIME媒體表現方式的類型。在這里指定的標示是"text/plain",實際就是返回普通的文本字符串信息。詳細的各種類型會在后面介紹。
3. 發布為RESTful service
1 package com.study.jersey.server; 2 3 import java.io.IOException; 4 import java.net.URI; 5 6 import javax.ws.rs.core.UriBuilder; 7 8 import org.glassfish.grizzly.http.server.HttpServer; 9 10 import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory; 11 import com.sun.jersey.api.core.PackagesResourceConfig; 12 import com.sun.jersey.api.core.ResourceConfig; 13 14 public class PublishService { 15 16 public static URI getBaseURI(){ 17 return UriBuilder.fromUri("http://localhost/").port(9998).build(); 18 } 19 20 public static final URI BASE_URI = getBaseURI(); 21 22 protected static HttpServer startServer() throws IllegalArgumentException, NullPointerException, IOException{ 23 System.out.println("Start server..."); 24 ResourceConfig config = new PackagesResourceConfig("com.study.jersey.server"); 25 return GrizzlyServerFactory.createHttpServer(BASE_URI, config); 26 } 27 public static void main(String[] args) { 28 try { 29 HttpServer httpServer = startServer(); 30 System.out.println(String.format("Jersey app started with WADL available at" + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...", BASE_URI, BASE_URI)); 31 System.in.read(); 32 httpServer.stop(); 33 } catch (IllegalArgumentException | NullPointerException | IOException e) { 34 e.printStackTrace(); 35 } 36 37 } 38 }
執行上面代碼,在console中會提示:
Jersey app started with WADL available athttp://localhost:9998/application.wadl Try out http://localhost:9998/helloworld Hit enter to stop it...
打開瀏覽器輸入http://localhost:9998/helloworld,可看到返回信息"Hello World!",如果輸入 http://localhost:9998/application.wadl,可以看到服務的xml描述. 在這里我們使用Grizzly將服務發布出來。這就實現了第一個簡單的RESTful服務。