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群进行交流

相关文章
相关标签/搜索