Home  >  Article  >  Java  >  Java Jersey2 usage summary

Java Jersey2 usage summary

高洛峰
高洛峰Original
2016-12-17 14:47:321486browse

Introduction

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

Core Server: By providing standardized annotations and API standardization in JSR 311, you can Develop RESTful web services in an intuitive way.​​

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

Integration (Integration): Jersey also provides libraries that can easily inherit spring, Guice, and Apache Abdera.​​

Jersey2.0 is used in this development, and only the core server is used.

Set up the Jersey environment

Maven

org.glassfish.jersey.containers jersey-container-servlet-core< ;/artifactId> 2.0 javax.xml.ws 2.1 org.codehaus.jacksonjackson-core-asl 1.9.12 org.codehaus.jackson 1.9.12 org.codehaus.jackson jackson-jaxrs< ;/artifactId> 1.9.12

Introduce the 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: You need to use Jackson1.9 in Jersey2.0 to support json.

Hello World

The following will show a Hello World

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

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

Step 2: Write JAX-RS application

public class APIApplication extends ResourceConfig {
public APIApplication() { //Load Resource register(HelloResource.class); //Register data converter register(JacksonJsonProvider.class); // Logging. register(LoggingFilter.class);
}
}

Step 3: In web. The servelt scheduler is defined in the 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.

JerseyServlet org.glassfish.jersey.servlet.ServletContainer< ;/servlet-class> javax.ws.rs.Application cn.com.mink.resource.APIApplication 1 JerseyServlet /services/*

Step 4: Test 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. You can use HTTP methods (such as: GET, POST, PUT and DELETE) to operate resources. 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.

In the following sample code,

Resources is a collection of resources composed of "/services" URI, and UserResource is a member resource composed of "/services/user" URI;

@Path("/services") public class Resources { @Path("/user") public UserResource getUserResource() { ... } @Path("/book") public BookResource getBookResource() { ... }
}

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

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

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 or collection of resources.​

HTTP ​ POST ​: Create a new resource. ​​

HTTP​​​​​PUT​​: Update existing resources or resource collections. ​​

HTTP​​​​​DELETE​​​: Delete a resource or resource collection. The 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 a method annotation. The @Produces annotation of the method will override the annotation of the class.

Specify a MIME type

@Produces("application/json")

Specify multiple MIME types

@Produces({"application/json","application/xml"})

@Consumes

@Consumes Contrary to @Produces , it is used to specify the MIME type that can be sent by the client. It can also be used for class or method. It can also specify multiple MIME types. It is 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 Jersey User Manual

@PathParam

Use @PathParam to get the parameters of the rules specified in the URI, such as:

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

...

}


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

@QueryParam

@QueryParam Used to get 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) {

          ...

}


When the browser requests                                                       use using using  -                                                 off ’ s       through out through out out through out out through out out out through off ‐  ‐‐ ‐‐‐ and ​ to , 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) {

...

}


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

@FormParam

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

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

@BeanParam

When there are many request parameters, for example, the client submits a PUT request to modify a user, and the request contains many pieces of user information. You can use @BeanParam at this time.

@POST@Consumes("application/x-www-form-urlencoded")public void update(@BeanParam User user) { // Store the user data}

User Bean is defined as follows:

@XmlRootElement(name = "user")
public class User { @PathParam("userName) 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; } ...
}

Use Map

in a large server, because of the parameters Changeable, parameter structure adjustment will encounter problems due to the above methods. At this time, you can consider using the @Context annotation and obtain the UriInfo instance, as follows:

@GET
public String get(@Context UriInfo ui) {
MultivaluedMap queryParams = ui.getQueryParameters();
MultivaluedMap pathParams = ui.getPathParameters();
}

can also be obtained through @Context annotation ServletConfig , ServletContext , HttpServletRequest , HttpServletResponse and HttpHeaders etc., as follows:

@Path("/")public class Resource { @Context HttpServletRequest req; @Context ServletConfig servletConfig; @Context ServletContext servletContext; @GET public String get(@Context HttpHeaders hh) { Multivalued Map pathParams = hh.getCookies(); }
}

Jersey returns Json and Xml

JAX-RS supports the use of JAXB (Java API for XML Binding) JavaBeans bind to XML or JSON and vice versa. JavaBean must be annotated with @XmlRootElement . Fields without @XmlElement annotation will contain an XML element with the same name, as follows:

@XmlRootElementpublic 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; }
}

Then use in REST service:

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

Finally, register the data converter, which will automatically convert JavaBean to json data:

public class APIApplication extends ResourceConfig {
public APIApplication() { //Load Model register(OptionResult.class) ; //Load Model with the same package as OptionResult //packages(OptionResult.class.getPackage().getName()); //Load Resource register(UserResource.class); //Register data converter register(JacksonJsonProvider.class ; For details, see Jersey User Manual

Problem Summary

Ajax requests (POST, PUT and DELETE) cannot submit data to the Jersey container

Problem Description

In the development of the SMS platform, all CRUD of data is completed using Ajax technology, so POST, PUT and DELETE requests must be used. The content-type of these three requests is "application/x-www-form-urlencoded". If UTF-8 encoding is used, it will become "application/x-www-form-urlencoded; UTF-8". In the process of debugging the program using Firefox's tamperdata extension, it was found that when the content-type is "application/x-www-form-urlencoded", the Jersey container can obtain the submitted data through the @FormParam annotation, and the content-type is " application/x-www-form-urlencoded; UTF-8" cannot be obtained.

Solution

Finally I solved the problem using Java Filter and Jersey RequestFilter. First, use UTF8 in Java Filter to encode the data in the Request, and then change the content-type in the request object to "application/x-www-form-urlencoded" in Jersey RequestFilter. For example:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; req.setCharacterEncoding("UTF-8");
}public class RequestFilter implements ContainerRequestFilter { @ Override public void filter(ContainerRequestContext context) throws IOException { String headerString = context.getHeaderString("content-type"); if (headerString != null) { //If content-type is "application/x-www-form-urlencoded" ", then process if (headerString.startsWith(MediaType.APPLICATION_FORM_URLENCODED)) context.getHeaders().putSingle("content-type", MediaType.APPLICATION_FORM_URLENCODED); } }
}

Finally register Java in web.xml Filter (to be registered before the Jersey container), register Jersey RequestFilter in APIApplication, as follows:

public class APIApplication extends ResourceConfig {
public APIApplication() {
 register(RequestFilter.class);
}
}

Instructions ​

: After fixing this problem, I saw in the Jersey source code repository on Github that someone has discovered and fixed this problem. This problem should not occur again in the next official version of Jersey. For details, please see this Discussion



For more articles related to Java Jersey2 usage summary, please pay attention to the PHP Chinese website!

Statement:
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