Home > Java > javaTutorial > Getting Started with Jersey and Javabeans

Getting Started with Jersey and Javabeans

高洛峰
Release: 2016-12-17 14:44:54
Original
1560 people have browsed it

Jersey is an open source reference implementation of JAX-RS (JSR311) for building RESTful Web services. It contains three parts:

  Core Server (Core Server) By providing standardized annotations and API standardization in JSR 311, it can be used in an intuitive way Develop RESTful web services.

Core Client Jersey client API can help developers easily communicate with RESTful services;

Integration Jersey also provides libraries that can easily inherit Spring, Guice, and Apache Abdera

Set up the Jersey environment

Maven

<!--jersey-->
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>2.0</version>
</dependency>

<!--JAXB API-->
<dependency>
    <groupId>javax.xml.ws</groupId>
    <artifactId>jaxws-api</artifactId>
    <version>2.1</version>
</dependency>

<!-- Json支持 -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.12</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-jaxrs</artifactId>
    <version>1.9.12</version>
</dependency>
Copy after login

Introduce Jar file method
Copy the following libraries from the Jersey development package to the library directory under WEB-INF:

 Server jersey-server.jar, jersey-container-servlet-core.jar, jersey-container- servlet.jar, javax.ws.rs-api-2.0.jar

 Client: jersey-client.jar

 common: jersey-common.jar

 Json support: Jackson1.9 is required in Jersey2.0 Support json.

Demo Hello Wolrd

Step 1: Write a resource named HelloResource, which accepts Http Get requests and responds with "Hello Jersey"

@Path("/hello")
public class HelloResource {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello() {
        return "Hello Jersey";
    }
}
Copy after login

Step 2: Write a JAX-RS application

public class APIApplication extends ResourceConfig {
    public APIApplication() {
        //加载Resource
        register(HelloResource.class);

        //注册数据转换器
        register(JacksonJsonProvider.class);

        // Logging.
        register(LoggingFilter.class);
    }
}
Copy after login

Step 3: In The servelt scheduler is defined in the web.xml file with the purpose of sending all REST requests to the Jersey container. In addition to declaring Jersey Servlet, you also need to define an initialization parameter to specify the JAX-RS application.

<!--用于定义 RESTful Web Service 接口-->
<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>cn.com.mink.resource.APIApplication</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JerseyServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>
Copy after login

Step 4: Test the program
Enter the following command in the command terminal and you will see "Hello Jersey".
curl http://host:port/services/hello
Or enter the following URL in the browser, you will see "Hello Jersey"
http://host:port/services/hello

Use

Resources

Root Resource And Sub-Resource
Resources are a key part of RESTful services, and resources can be operated using HTTP methods (such as GET, POST, PUT and DELETE). In JAX-RX, resources are implemented through POJOs, using @Path annotations to form their identifiers. Resources can have child resources. The parent resource is a resource collection and the child resources are member resources.
Resources is a collection of resources composed of "/services" URI, and UserResource is a member resource composed of "/services/user" URI;

Note that POJO refers to a simple Java object

@Path("/services")
public class Resources {

    @Path("/user")
    public UserResource getUserResource() {
        ...
    }

    @Path("/book")
    public BookResource getBookResource() {
        ...
    }
}
Copy after login

UserResource is composed of "/user" URI Collection resources, getUser is a resource method composed of "/user/{username}" URI

The contents in the curly brackets are parameters. This setting is reasonable, because username will also appear in the URL, and path means URL

@Path("/user")
public class UserResource {
    @GET
    @Path("{username"})
    @Produces("application/json")
    public User getUser(@PathParam("username") String userName) {
        ...
    }
}
Copy after login

HTTP Methods
HTTP methods are mapped to CRUD (create, read, update and delete) operations of resources. The basic modes are as follows:

 HTTP GET: Read/list/retrieve a single resource

 HTTP POST: Create a new resource

  HTTP PUT: Update existing resources or resource collections

HTTP DELETE: Delete resources or resource collections

@Produces
@Produces annotation is used to specify the data identification type (MIME) to be returned to the client. @Produces can be used as a class annotation or as a method annotation. The @Produces annotation of the method will override the annotation of the class. The meaning of overwriting is that if the method declares its own Produce, then the method shall prevail, and the class shall be for reference only.
Specify the MIME type
@Produces("application/json")
Specify multiple MIME types
@Produces({" application/json","application/xml"})

@Consumes
@Consumes is the opposite of @Produces. It is used to specify the MIME type that can be accepted from the client. It can also be used for class or method, or multiple MIMEs can be specified. Type, generally used for @PUT, @POST.

Parameter Annotations
Parameter Annotations are used to obtain the data sent by the client. This article only introduces commonly used annotations. For more details, see the Jersey User Manual
@PathParam
Use @PathParam to get the parameters of the specified rule in the URI, such as:

@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
    ...
}
Copy after login

When the browser requests http://localhost/user/jack, The userName value is jack.

Note that username here does not mean that Key is username and value is jack, but that what follows /usr/ is username. Here username is just a variable

As for the form of key and value, there are also the following

@QueryParam
@QueryParam is used to obtain the query parameters in the GET request, such as:

@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
                    @QueryParam("age") int age) {
    ...
}
Copy after login

When the browser requests http://host:port/user?name=rose&age=25, the name value is rose and the age value is 25. If you need to set a default value for a parameter, you can use @DefaultValue, such as:

@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name,
                    @DefaultValue("26") @QueryParam("age") int age) {
    ...
}
Copy after login

When the browser requests http://host:port/user?name=rose, the name value is rose and the age value is 26.

@FormParam
@FormParam, as the name suggests, gets data from the form parameters of the POST request. Such as:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}
Copy after login

表单我一直没弄清楚到底是什么东西,但就使用的情况来看,就是key,value之类的东西

BeanParam
当请求参数很多时,比如客户端提交一个修改用户的PUT请求,请求中包含很多项用户信息。这时可以用@BeanParam。
User Bean定义如下:

@XmlRootElement(name = "user")
public class User {
    @PathParam("userName) //我觉得这个应该是写错了,FormParam
    private String userName;

    @FormParam("name")
    private String name;

    @FormParam("telephone")
    private String telephone;

    @FormParam("email")
    private String email;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    ...
}
Copy after login

使用Map
在一个大型的server中,因为参数的多变,参数结构的调整都会因为以上几种方式而遇到问题,这时可以考虑使用@Context 注释,并获取UriInfo实例,如下:

@GETpublic String get(@Context UriInfo ui) {
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
    MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}
Copy after login

我觉得,可以认为map是上面几种情况的超集,因为它能够替代以上任意一种。map就是context

同样还可以通过@Context 注释获取ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等,如下:

@Path("/")
public class Resource {

    @Context
    HttpServletRequest req;

    @Context
    ServletConfig servletConfig;

    @Context
    ServletContext servletContext;

    @GET
    public String get(@Context HttpHeaders hh) {
        MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
        Map<String, Cookie> pathParams = hh.getCookies();
    }
}
Copy after login

Jersey返回Json和Xml
JAX-RS支持使用JAXB(Java API for XML Binding)将JavaBean绑定到XML或JSON,反之亦然。JavaBean必须使用@XmlRootElement标注,没有@XmlElement注释的字段将包含一个名称与之相同的XML元素,如下:

这里就说明了javabean和xml, json的关系

@XmlRootElement
public class OptionResult {
    @XmlElement(name = "code")
    private String result;

    private String errorMsg;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
Copy after login

然后在REST服务中使用:

@Path("/user")
public class UserResource {
    @POST
    @Produces("application/json")
    public OptionResult create(@BeanParam User user) {
        ...
    }
}
Copy after login

最后,要注册数据转换器,该转换器会自动将JavaBean转换为json数据:

public class APIApplication extends ResourceConfig {
    public APIApplication() {
        //加载Model
        register(OptionResult.class);

        //加载与OptionResult同一个packge的Model
        //packages(OptionResult.class.getPackage().getName());

        //加载Resource
        register(UserResource.class);

        //注册数据转换器
        register(JacksonJsonProvider.class);

        // Logging.
        register(LoggingFilter.class);
    }
}
Copy after login

说明:返回XML数据的原理相同,仅仅是数据转换器不同,只需要在APIApplication中同时XML数据转换器即可。

Wiki上关于REST的总结

含状态传输(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格.

  资源是由URI来指定。

  对资源的操作包括获取、创建、修改和删除资源,这些操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法。

  通过操作资源的表现形式来操作资源。

  资源的表现形式则是XML或者HTML,取决于读者是机器还是人,是消费web服务的客户软件还是web浏览器。当然也可以是任何其他的格式。

应该注意区别应用的状态和连接协议的状态。HTTP连接是无状态的(也就是不记录每个连接的信息),而REST传输会包含应用的所有状态信息,因此可以大幅降低对HTTP连接的重复请求资源消耗。

实现举例:

每种操作都会对应一个函数

列举所有商品

GET http://www.store.com/products

呈现某一件商品

GET http://www.store.com/product/12345

下单购买

POST http://www.store.com/order ...

REST的优点

  可更高效利用缓存来提高响应速度

  通讯本身的无状态性可以让不同的服务器的处理一系列请求中的不同请求,提高服务器的扩展性

  浏览器即可作为客户端,简化软件需求

  相对于其他叠加在HTTP协议之上的机制,REST的软件依赖性更小

  不需要额外的资源发现机制

  在软件技术演进中的长期的兼容性更好

JavaBean

JavaBeans是Java语言中可以重复使用的软件组件,它们是一种特殊的Java类[1],将很多的对象封装到了一个对象(bean)中。特点是可序列化,提供无参构造器,提供getter方法和setter方法访问对象的属性。

优点

  Bean可以控制它的属性,事件和方法是否暴露给其他程序

  Bean可以接收来自其他对象的事件,也可以产生事件给其他对象

  有软件可以配置Bean

  Bean的属性可以被序列化,以供日后使用

JavaBean规范

要成为JavaBean类,必须遵循关于命名,构造器,方法的特定规范,有了这些规范,才能使用,复用,替代和连接javabean的工具。
规范是:

  有一个public 无参构造器

  属性可以通过get, set, is方法或者遵循特定命名规范的其他方法访问。

  可序列化

一个例子

public class PersonBean implements java.io.Serializable {

    /**
     * <code>name</code>属性(注意大小写)
     */
    private String name = null;

    private boolean deceased = false;

    /** 无参构造器(没有参数) */
    public PersonBean() {
    }

    /**
     * <code>name</code>属性的Getter方法
     */
    public String getName() {
        return name;
    }

    /**
     * <code>name</code>属性的Setter方法
     * @param value
     */
    public void setName(final String value) {
        name = value;
    }

    /**
     * "deceased"属性的Getter方法
     * 布尔型属性的Getter方法的不同形式(这里使用了is而非get)
     */
    public boolean isDeceased() {
        return deceased;
    }

    /**
     * <code>deceased</code>属性的Setter方法
     * @param value
     */
    public void setDeceased(final boolean value) {
        deceased = value;
    }
}
Copy after login

总结

1. Javabean提供了一种保证,即对于所有的成员变量,一定有get,set方法。并且还可以序列化

2. REST服务基于底层的保证来实现,因此可以简化很多事情,比如Javabean和XML的转换就可以写得相当简单。



更多Jersey 入门与Javabean相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template