本文參考:https://www.jianshu.com/p/88f97b90963c
Jersey RESTful 框架是開源的RESTful框架, 實現了JAX-RS (JSR 311 & JSR 339) 規範。它擴展了JAX-RS 參考實現, 提供了更多的特性和工具, 可以進一步地簡化 RESTful service 和 client 開發。
開發環境:eclipse、 Gradle
使用內置容器方式
1 創建 gradle 項目
build.gradle文件引用
compile 'org.glassfish.jersey.containers:jersey-container-jetty-http:2.29.1'
compile 'org.glassfish.jersey.inject:jersey-hk2:2.29.1'
2 REST服務類
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 HelloService { @GET @Produces(MediaType.TEXT_PLAIN) public String hi(){ return "hello jersey"; } }
說明:
1 包名test,發步服務時要包括此包名
2 @Path("hello"),代表資源根路徑爲hello
3 方法hi上面添加了兩個標籤,@GET標籤代表該方法接受GET類型請求 @Produces標籤代表該方法的響應MIME類型爲text/plain
4 該方法返回String,這個String值Jersey會自動按照text/plain格式輸出
3 創建一個Application類,用於設置發佈環境
package test import org.glassfish.jersey.server.ResourceConfig; public class RestApplication extends ResourceConfig{ public RestApplication(){ this.packages("test"); } }
說明:
在RestApplication類的構造方法中,調用了packages方法註冊了掃描資源類的基礎包
4 發佈應用
import java.net.URI; import org.glassfish.jersey.jetty.JettyHttpContainerFactory; public class Test { public static void main(String[] args) { RestApplication restApplication= new RestApplication(); JettyHttpContainerFactory.createServer(URI.create("http://localhost:8082/"),restApplication); } }
5 客戶段測試
可以通過瀏覽器或是restclient工具訪問 http://localhost:8082/hello
restclient工具下載網址:windows操作系統下載restclient-ui-fat-版本號.jar
https://github.com/wiztools/rest-client/releases
機器上安裝jdk環境後,爲了方便
測試效果