本文參考以下內容:
使用Jersey實現RESTful風格的webservice(一)
Starting out with Jersey & Apache Tomcat using IntelliJ
--------------------------------------------------正文--------------------------------------------------------------
一、在IntelliJ中創建新項目,選擇Java Enterprise -> RESTful Web Service -> Setup libery later.
二、創建完項目JerseyDemo后,對項目點擊右鍵 -> Add Frameworks Support,分別勾選Web Application和Maven。其中,web appication為項目增加了web.xml,maven為構建工具。
完成之后項目的文件結構如下:
三、在pom.xml中加入jersey和jetty依賴:
<dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-bundle</artifactId> <version>1.19.1</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty</artifactId> <version>6.1.25</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.19</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.19.1</version> </dependency> </dependencies>
四、在src/main/java/下創建package和類,這里我創建了一個HelloJsersy類,代碼如下:
package com.puyangsky.example; import javax.ws.rs.*;
//Path注解來設置url訪問路徑 @Path("/hello") public class HelloWorld {
//GET注解設置接受請求類型為GET @GET
//Produces表明發送出去的數據類型為text/plain
//與Produces對應的是@Consumes,表示接受的數據類型為text/plain
@Produces("text/plain") public String getString() { return "hello jersey!"; } }
接着使用Jetty創建一個服務器類StartEntity.java:
1 package com.puyangsky.example; 2 3 import com.sun.jersey.api.core.PackagesResourceConfig; 4 import com.sun.jersey.spi.container.servlet.ServletContainer; 5 import org.mortbay.jetty.Server; 6 import org.mortbay.jetty.servlet.Context; 7 import org.mortbay.jetty.servlet.ServletHolder; 8 9 /** 10 * Created by user01 on 2016/4/8. 11 */ 12 public class StartEntity { 13 public static void main(String[] args) { 14 Server server = new Server(8090); 15 ServletHolder sh = new ServletHolder(ServletContainer.class); 16 sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", PackagesResourceConfig.class.getCanonicalName()); 17 sh.setInitParameter("com.sun.jersey.config.property.packages", "com.puyangsky.example"); 18 //start server 19 Context context = new Context(server, null); 20 context.addServlet(sh, "/*"); 21 try { 22 server.start(); 23 server.join(); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 28 } 29 }
紅色字體標出的第一個是端口號,可以自己設置,第二個是需要你自己修改的,即第一個HelloJersey.java所在的包名。
ok,點擊右鍵,Run "StartEntity.main()"
五、在瀏覽器中訪問http://localhost:8090/hello,或使用IntelliJ中的Test RESTful Web Service,結果如下:
大功告成!
------------------------------------------------------一些小建議------------------------------------------------
1、IntellJ的快捷鍵:
神器之所以是神器,當然有不一樣的地方,比如我們想寫一個main方法,不用輸入一大串,只要輸入“psvm”,回車,搞定!
類似的還有輸出,只要輸入“souf”,右鍵。類的還有很多,自己去慢慢發現。
2、Jetty占用了端口號沒有釋放,每次都換一個端口號很麻煩,那么應該怎么辦?
因為我是在windows7上做的,那么win+R打開DOS命令行,輸入netstat -ano | findstr "8090":
最后一欄為進程ID,pid.所以只要kill掉就ok了,接着輸入:taskkill /PID 12336 /F
結果:
這里因為12236已經掛了所以換了個PID,效果一樣。
Jersey的更多使用將在下一篇博客中繼續介紹。