Jersey構建REST服務入門

要設置開發環境,您須要如下內容html

  • IDE:Eclipse IDE java

  • Jdkweb

  • Web 容器:Apache Tomcat 7.0json

  • Jersey 庫:Jersey ,包含全部必需的庫瀏覽器

在Eclipse中建立一個web工程tomcat

 

首先,爲 Eclipse 上的 Tomcat建立服務器運行時。這是用於 RESTful Web 應用程序的 Web 容器。而後建立一個名爲 「RestDemo」 應用程序,並將目標運行時指定爲 Tomcat 。服務器

最後,從 Jersey 開發包中將如下庫複製到 WEB-INF 下的庫目錄微信

方法 資源集合, URI 如:
http://host/<appctx>/resources
成員資源,URI 如:
http://host/<appctx>/resources/1234
GET 列出資源集合的全部成員。 檢索標識爲 1234 的資源的表示形式
PUT 使用一個集合更新(替換)另外一個集合。 更新標記爲 1234 的數字資源。
POST 在集合中建立數字資源,其 ID 是自動分配的。 在下面建立一個子資源。
DELETE 刪除整個資源集合。 刪除標記爲 1234 的數字資源。

 

一、@Pathapp

@Path 註釋被用來描述根資源、子資源方法或子資源的位置ide

cn.com.service包下建立第一個helloworld

package cn.com.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
 
@Path("/restService")
publicclass Hello {
 
      @Path("/getHello")
      @GET
      public  String getHello() {
           // TODO Auto-generated constructor stub
           return"helloWorld";
      }
 
}

二、將Hello服務部署發佈

1)配置web.xml文件

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID"version="3.0">
    <display-name>RestDemo</display-name>
    <servlet>
        <servlet-name>testDemo</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!--        初始化servlet範圍內的參數 -->
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>cn.com.info.RestApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>testDemo</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

2)在包cn.com.info.RestApplication下建立RestApplication

public classRestApplicationextends ResourceConfig {
      public RestApplication() {
           // 服務類所在的包路徑
           packages("cn.com.service");
           //註冊JSON轉換器
           register(JacksonJsonProvider.class);
           // 打印訪問日誌,便於跟蹤調試,正式發佈可清除
           register(LoggingFilter.class);
      }
}

 

3)將項目部署到tomcat,

啓動服務輸入http://localhost:8080/RestDemo/rest/restService/getHello

查看返回結果爲「hello」

三、@Path("/users/{username}")和@PathParam

@path(「/users/{username}」)username爲在url後面緊跟的參數,若是要獲取到就用@PathParam

 

package cn.com.service;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@Path("/restService")
public class HelloParam {
      @Path("/getHello/{username}")
      @GET
     
      public  String getHello(@PathParam("username") String username) {
            // TODO Auto-generated constructor stub
            return username;
      }
}

輸入http://localhost:8080/RestDemo/rest/restService/getHello/Liliei

返回信息爲:Lilei

 

4、@Conumes 和 @Produces和@FormParam

@Consumes 註釋表明的是一個資源能夠接受的 MIME 類型。

@Produces 註釋表明的是一個資源能夠返回的 MIME 類型。這些註釋都可在資源、資源方法、子資源方法、子資源定位器或子資源內找到

@FormParam,請求的數據來源於表單中的參數

 

package cn.com.service;
 
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces; 
 
@Path("/restService")
public class FormPostParam {
 
      @Path("/getPost")
      @POST
      @Consumes("application/x-www-form-urlencoded")
      @Produces("text/plain")
      
      public  String  getPost(@FormParam("name") String name) {
            // TODO Auto-generated constructor stub
            return name;
      }
}

使用restClient,調取http://localhost:8080/RestDemo/rest/restService/getPost

Post參數name=helloTest

查看後臺日誌信息

五、@Context獲取上下文

  @Path("/getHeaders")
      @GET
      @Produces("application/json; charset=UTF-8")
      public String getHeader(@Context HttpHeaders hh) {
          MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
 
          returnheaderParams.toString();
            }

使用RestClient輸入http://localhost:8080/RestDemo/rest/restService/getHeaders

返回:{host=[localhost:8080], connection=[Keep-Alive], user-agent=[Apache-HttpClient/4.4 (Java 1.5 minimum; Java/1.8.0_51)], accept-encoding=[gzip,deflate]}

六、@DefaultValue和@QueryParam

@DefaultValue,默認值

@QueryParam查詢時傳入的參數值,列XXXXXXXX:8080/ddd?in=1&from=3

 

@Path("/restService")
publicclass DefaultValues {
      @Path("/getDefaultValue")
      @GET
      public  String getDefaultValue(@DefaultValue("1000") @QueryParam("from") intfrom,
              @DefaultValue("999")@QueryParam("to") intto) {
           return"getDefaultValue is called, from : " + from + ", to : " + to;
      }
}

瀏覽器輸入:http://localhost:8080/RestDemo/rest/restService/getDefaultValue

獲得結果:getDefaultValue is called, from : 1000, to : 999

瀏覽器輸入:http://localhost:8080/RestDemo/rest/restService/getDefaultValue?from=9&to=12

獲得結果:getDefaultValue is called, from : 9, to : 12

 

 

 

歡迎你們關注微信公衆號與QQ羣進行交流

相關文章
相關標籤/搜索