Jax-rs (Java API for RESTful Web Service) _1.1 parsing

Source: Internet
Author: User
Tags java se
What's jax-rs?

Jax-rs (Java API for RESTful Web service,jsr-311) is a Java-provided API for developing RESTful Web services based on annotations (annotation), published in Java EE 6, designed to define a unified specification , enabling Java programmers to use a fixed set of interfaces to develop rest applications, avoiding reliance on third-party frameworks, and Jax-rs using the Pojo programming model and annotation-based configuration and integrating JAXB, effectively shortening the rest application development cycle, JSR-311 began in February 2007 and has released two final versions of 1.0,1.1, and it is noteworthy that jax-rs2.0 (JSR-339, beginning in January 2011) is in progress;

(By the way, Java is called open technology because of the JSR (Java specification Requests), any organization and individual can bring a JSR to JCP (Java Community Process), After review by the expert group can be published in subsequent Java version as a new feature, Java development is through the JCP to promote. Jax-rs API Overview

JAX-RS defines the package structure as follows, contains nearly 50 interfaces, annotations, and abstract classes:

Javax.ws.rs: Contains high-level (high-level) interfaces and annotations for creating restful service resources;

Javax.ws.rs.core: Contains low-level (low-level) interfaces and annotations for creating restful service resources;

Javax.ws.rs.ext: Contains APIs for extending the type of Jax-rs API support;

Note: The JAX-RS specification simply defines the API, and the real development of restful Web services requires the introduction of concrete implementations that are provided by third parties, such as Sun's reference implementation Jersey,apache Cxf,jboss Resteasy; jax-rs The objective of the API is based on Pojo: The API provides a set of annotations, classes, interfaces for exposing POJOs to network resources (Web Resource), and defining the lifecycle and effective scope of an object; HTTP-centric: The specification uses the default HTTP as the underlying network protocol and provides a clear mapping between HTTP and URI elements to API classes and annotations, which provides support for common HTTP usage patterns and various HTTP applications, including the Webdav,atom Publishing protocol ; format-Independent: The API will be able to handle HTTP entities in a variety of different content formats, and provide a unified extension mechanism to allow applications to add new support to other content formats (via entity provider); container-Independent: Applications that use this API can be deployed to multiple web containers. The specification will define how the application is deployed in the servlet container and as a JAX-WS provider, incorporating Java EE: The specification will define the environment of the network resource (Web Resource) class in the Java EE Container and will guide how to use the functionality and components provided by Java EE;

The following are not the objectives of the JAX-RS API: Support j2se5.0 versions: The API expands and uses annotation functionality, requires j2se5.0 or later, describes, registers, and discovers: The specification is undefined and does not require any service description, registration and discovery functions; Client API: The specification does not define client APIs and expects other specifications to provide that functionality; HTTP stack: The specification does not define a new HTTP stack, and HTTP protocol support is a container that is applied through deployment using the API; Data model/Format class: The specification does not define a class for manipulating entity content. Instead, it provides an extension mechanism that allows these classes to be used using the application definitions of the API; Jax-rs main Interface/class introduction Application (application)

A JAX-RS application consists of one or more resource (Resource) classes and 0 or more provider, the resource (Resource) class that makes up the Jax-rs application, and the provider is configured by applying the provided application subclass Jax-rs third-party implementations can provide additional mechanisms for discovering resource (Resource) classes and provider (e.g., runtime automatic scanning), but using application is the only portable method (each implementation must support);

How the application (application) is published: Java SE: Published in the SE environment through JAX-WS Javax.xml.ws.Provider; Servlet: Package Jax-rs applications as. War files as Web application publishing; Resources (Resource)

In Jax-rs, a resource class represents a network resource, and any request to that network resource is handled by the method defined in the resource class, in Java, a resource is a Pojo class, At least one of the methods is labeled by @path or HTTP method indicators (such as @get, @POST, @PUT, @DELETE, @OPTIONS); 1, Life cycle

By default each request creates a new resource instance to process the request;

The procedure is shown in the following illustration:


Figure 1: Each request to the resource creates an instance

Note: Implementations can provide support for other lifecycles of resource classes (such as IOC container Management resource classes) 2, builder

The root resource class is initialized by the Jax-rs runtime, so you must provide a public constructor (which can be provided by the runtime with parameters, or without parameters), and the non-root resource class does not have to be initialized by applying; the parameters of the public constructor can be: @Context, @ Headerparam, @CookieParam, @MatrixParam, @QueryParam and @pathparam are annotated, and when there are multiple public constructors, the implementation needs to select one of the most parameters, and when there are more than one number of parameters the same constructor, Implementation can choose a suitable according to their own way, and can issue alarms; 3, Fields and properties

When a resource class is instantiated, field and bean properties can be initialized with the following annotations:

@MatrixParam: Get the value of the URI matrix parameter;

@QueryParam: Gets the value of the URI query parameter;

@PathParam: Obtain the value of the URI template parameter;

@CookieParam: Get cookie value;

@HeaderParam: Gets the value of the HTTP request header;

@Context: Injecting other context instances;

The annotations above, in addition to @context, are related to the current specific request, so if the implementation provides a resource class other lifecycle should be careful to use these annotations for field and bean properties; 4, Resource methods

A resource method is a method of the requested method designator in a resource class that handles different HTTP requests, the request method indicator is a run-time annotation that is @httpmethod annotated, and Jax-rs defines a set of request method indicators for a common HTTP method: @GET, @POST, @ Put, @DELETE, @HEAD, users can also use @httpmethod to customize the request method indicator; Visibility: Only the public method can be used as a resource method; parameter: A resource method parameter can be @formparam and annotated with the above field, @ DefaultValue is used to provide a default value for a parameter, @Encoded used to specify an automatic URI decoding parameter value, a parameter that is not annotated (called an entity parameter) is used to map the entity portion of the request, and the conversion between the entity part and the Java type is provided by the entity provider. Information about Provider is described in the following section (Provider); return type: The resource method can return void,response,genericentity, or other Java types, which are mapped to the response entity as follows; void: Returns a 204 status code, the response body is empty, the Response:response entity property as the response body, the Status property as the status code, if no status is set, and the status is 204 when entity is empty, The Entity property of Genericentity:genericentity, which is not NULL, is the response body, and when the return value Non-null, the status code is 200, and the state code is 204 when it is null; Other Java types: Returns the instance as the response body, when the return value is Non-null, the status code is 200, and the status code is 204 when it is null; 5,uri template

The root resource class is mapped to a URI address space through @path, which is a relative URI path based on the combination of deployment contexts (context) and application path (see @applicationpath);

A URI template is a string that contains 0 or more embedded parameters, and when all the arguments are submitted, a valid URI is formed;

As follows: Java code @Path ("Widgets/{id}") public class widget{...}

In the example above, the Widget resource class is positioned widgets/xxx the relative URI path, where xxx is the value of the ID parameter;

The @Path values are automatically encoded, and the following two annotations are equivalent:

@Path ("Widget List/{id}")

@Path ("Widget%20list/{id}")

Template parameters can use regular expressions to match values, such as: Java code @Path ("widgets/{path:.+}") public class widget{...}

In the above example, the Widget resource class will be matched to a request that the path starts at widgets and contains at least one path fragment (segment), and the path parameter value is a widgets/string, such as the request path is widgets/small/a and the path parameter value is small/a;

6, Child resources

The method that is @path annotated in the resource class is either a child resource method (Sub-resource methods) or a child resource Locator (Sub-resource locators), and a child resource method can directly handle the HTTP request. The child resource Locator returns an object (which can also contain a child resource locator) to handle the HTTP request;

The resource method exists or is missing a request method indicator (designator), if the following are different:

1, exist, these methods (called Child resource Methods) will be considered as a normal resource method in addition to being able to handle matching URI requests;

2, Missing, these methods (called Child Resource Locators) are used to dynamically generate objects to process requests, and return objects are treated as resource class instances for processing requests (through child resource methods) or further generating objects to process requests (through a child resource locator);

Example Description: Java code @Path ("Widgets") public class Widgetsresource {@GET @Path ("offers") public widgetlist Getdiscoun      Ted () {...}   @Path ("{ID}") public Widgetresource Findwidget (@PathParam ("id") String ID) {return new Widgetresource (ID);      } public class Widgetresource {public widgetresouce (String ID) {...}   @GET public Widget getdetails () {...} }

In the example above, the GET request for widgets/offers is processed directly by the Widgetsresource method getdiscounted the resource class, and the widgets/ The GET request for XXX is processed by the Getdetail method of the Widgetresource resource class; 7, declaring the media type

The

application can be @consumes, @Produces to declare the request separately, and respond to the supported media type; This annotation can be applied to resource methods, resource classes, or entity providers (Provider) ; Using these annotations on resource methods overrides the resource class and entity provider (Provider) annotations to the method parameter/return type; By default, all media types (*/*) are supported;

Example Description: Java code @Path ("Widgets") @Produces ("APPLICATION/WIDGETS+MXL") public class Widgetsresouce {@GET P      Ublic Widgets getasxml () {...}      @GET @Produces ("text/html") public String getashtml () {...}   @POST @Consumes ("Application/widgets+xml") public void AddWidget (widget widget) {...} @Provider @Produces ("Application/widgets+xml") public class Widgetsprovider implements Messagebodywriter<wid      gets> {...} @Provider @Consumes ("Application/widgets+xml") public class Widgetprovider implements Messagebodyreader<widget > {...}

As above: The Getasxml resource method is called to process a GET request and the response to the entity media type is application/widgets+xml, and the widgets instance returned by the method will be widgetsprovider mapped to application/ Widgets+xml type (see Messagebodywriter); The getashtml resource method is called to process a GET request and the response Entity media type is text/html, and the string that the method returns contains text/ HTML will be implemented by default messagebodywriter<string> write back to the client; the AddWidget resource method is called to process the POST request and the request Entity media type is application/widgets+xml. The request entity will be mapped to the widget parameter via Widgetprovider (see Messagebodyreader); 8, note inheritance

Jax-rs annotations can be used for methods and method parameters of the superclass/interface, these annotations can be inherited if the subclass/implementation class has no annotations on the corresponding method, the annotation of the method in the parent class/interface is ignored if the subclass/implementation class has any annotations on the corresponding method;

The example illustrates: Java code public interface Readonlyatomfeed {@GET @Produces ("Application/atom+xml") Feed getfeed ();   @Path ("Feed") public class Activitylog implements Readonlyatomfeed {public feed getfeed () {...} }   }

In the example above, Activitylog.getfeed inherits the Readonlyatomfeed.getfeed @get and @produces annotations; instead: Java code @Path ("Feed") public class   Activitylog implements Readonlyatomfeed {@Produces ("application/atom+xml") public Feed getfeed () {...} }

In the example above, the @get annotation of readonlyatomfeed.getfeed is not inherited by Activitylog.getfeed, so the method needs to mark the request method indicator itself because it is @produces annotated.

provider (Provider)

The JAX-RS runtime extends through the application of the provided provider class; The provider is a class that is @provider annotated and implements one or more jax-rs interfaces; 1, Lifecycle

Default a JAX-RS application in which each provider has only one instance (the singleton, which is the opposite of resource); (implementations can support provider other lifecycles, such as managing all provider through the IOC container); 2, builder

The provider class is initialized by the Jax-rs runtime and requires a public constructor (either with a run-time supply with parameters or without parameters), and constructor parameters can be @context annotated because the creation of provider is beyond the specific request-related. Note here that the difference with the resource is so that only deployment-related information can be injected at creation time, and the information related to the specific request is visible when the provider method is invoked, and if there are more than one public constructor, the implementation should select one of the most parameters. If there is a constructor with the same number of parameter numbers, the implementation should give an alarm; 3, Entity provider

Entity provider is used to map between a request/response entity and a Java type: Messagebodyreader (the request entity maps to a Java type) and Messagebodywriter (the Java type maps to the response entity); message body Reader

The Messagebodyreader interface defines the relationship between the Jax-rs runtime and the components that provide the ability to map entities to Java types, and a class that provides the functionality needs to implement the Messagebodyreader interface and be @provider annotated;

JAX-RS implements the logical steps for processing request entities to Java method parameter mappings as follows:

1, obtain the requested media type and use Application/octet-stream if the request does not contain the Content-type request header;

2, determine the Java type of the parameter, which can map the processing request entity;

3, obtains the Messagebodyreader provider class collection which can support the request media type;

4, traversing the Messagebodyreader class collection, calling the IsReadable method to select the provider class that supports the desired Java type;

5, if a suitable messagebodyreader class is identified in step 4th, call the Readfrom method to map the request entity to the desired Java type object;

6, otherwise find a suitable data processor through the JavaBeans activation framework to map the request entity to the desired Java type;

7, otherwise generate webapplicationexception, containing a response (415) and an empty entity that does not support the media type; message body Writer

The Messagebodywriter interface defines the relationship between the Jax-rs runtime and the components that provide the mapping of Java types to the entity functionality, and a class that provides the functionality needs to implement the Messagebodywriter interface and be @provider annotated;

The logical steps of the JAX-RS implementation for handling Java return types to response entities are as follows:

1, get the object to be mapped as the response body, if the return type is response or its subclass, take the value of the Entity property, and the other type to take the value of the returned object;

2, determine the media type of the response entity;

3, obtains the Messagebodywriter provider class collection which can support the response media type;

4, sort the messagebodywriter by the similarity degree of the type;

5, traversing the Messagebodywriter class collection, calling the IsWriteable method to select the provider class that supports mapping Java objects to response entities;

5, if a suitable messagebodywriter class is identified in step 4th, the WriteTo method is called to map the Java object as a response entity;

6, otherwise the Java object is mapped as a response entity by looking for a suitable data processor through the JavaBeans activation framework;

7, otherwise generate Webapplicationexception, contains one server internal error response (500) and empty package body; declaring media type

The message body reader and writer can limit the types of media they support by @consume, by default, all media types (*/*) are supported, and when provider are selected, the implementation should be able to sort them by the type of media they support. Common collations for media types: x/y < x/* < */*; standard entity provider

Implementations need to provide commonly used messagebodyreader and messagebodywriter, with specific supported Java types and media types combined as follows:

Byte[] */*

Java.lang.String */*

Java.io.InputStream */*

Java.io.Reader */*

Java.io.File */*

Javax.activation.DataSource */* 4, Context Provider

Used to provide contexts to resource classes and other provider; a context provider class needs to implement the Contextresolver<t> interface and be @provider annotated. For example, to provide a custom jaxbcontext for the JAXB entity provider, you need a class implementation contextresolver<jaxbcontext> interface; declaring a media type

Context provider can restrict the type of media they support by @consume, by default, all media types (*/*) are supported, and when provider are selected, the implementation should be able to sort them by the type of media they support. Common collations for media types: x/y < x/* < */* 5, exception mapping provider

When a resource or provider method throws an exception, the Jax-rs runtime should be able to map the exception to an appropriate HTTP response, which can be customized using the exception map provider The exception map provider a checked or Run-time exception to a response instance, and an anomaly mapping provider class needs to implement the Exceptionmapper<t> interface and is @provider annotated; Context 1, concurrency

Contexts (context) correspond to specific requests and JAX-SR components (providers and those that are not singleton) may need to support multiple concurrent requests, and when injected into a context, the component instance should be able to select the correct context for the specific request. Using thread-local is a common method (e.g. tomcat,spring internal implementation uses THREADLOACL);

Context type: 2,application

An application-provided application subclass can be injected into the fields and method parameters of other classes through @context, and the application subclass is used to unify access to the configuration information; 3,uri template

A Uriinfo instance can be injected into the class's properties and method parameters by @context, and Uriinfo provides static and dynamic information about each request regarding the URI component element;

The following example shows all the queries that get the request (query

Parameter: Java code @GET @Produces {"Text/plain"} public String Listqueryparam (@Context uriinfo info) {StringBuilder buf =   New StringBuilder ();       For (String param:info.getQueryParameters (). Keyset ()) {buf.append (param);   Buf.append ("\ n");   return buf.tostring (); }

4,header

A httpheaders instance can be injected into the properties and method parameters of the class by @context; Httpheaders provides access request header information;

The following example shows all request header information for the request: Java code @GET @Produces {"Text/plain"} public String Listheadernames (@Context httpheader headers)   {StringBuilder buf = new StringBuilder ();       For (String param:header.getRequestHeaders (). Keyset) {buf.append (header);   Buf.append ("\ n");   return buf.tostring (); }

5, content negotiation and precondition

Jax-rs supports content negotiation and preconditions through the request interface, and a request instance is injected into the class's properties and method parameters through @context.

The following example shows checking the current entity tag before updating the resource

Whether to match the precondition: Java code @PUT public Response Updatefoo (@Context request, Foo foo) {Entitytag tag = Getcurrenttag (   );   Responsebuilder builder = request.evaluatepreconditions (tag);   if (builder!= null) return Builder.bulid ();   Eblse return DoUpdate (foo); }

6, security context

The SecurityContext interface provides access to the security context of the current request, and a SecurityContext instance is injected into the field and method parameters of the class through the @context, with SecurityContext accessible to users, roles, and authorization information. 7,providers

The providers interface can find provider instances based on a set of query criteria, and a providers instance can be injected into the field and method parameters of the class through @context, which is provider used to obtain and use the functions provided by other provider; Environment (Environment)

Which container-managed resources can be used by Jax-rs root resource classes and provider depending on the environment in which they are deployed;

servlet container: servlet-based JAX-RS implementation supports deploying JAX-RS applications to the servlet container and injecting servlet-related information into the application's resource and provider classes: ServletConfig, Servletcontext,httpservletrequest,httpservletresponse;

Jee Containers: JAX-RS implementations based on JEE containers should support ejb,managed beans as root resource classes, provider and application subclasses; Summary

This article is mainly based on the English version of the jax-rs1.1 specification translation, unlike the specification is the main story of JAX-RS programming elements (for application developers rather than the implementation of the specification) such as: application and its subclasses, Resource,provider,context rather than how to implement the specification and join the The entire jax-rs1.1 English original specification altogether 51 pages, the interest friend may download the detailed research;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.