Jax-rs\jersey Framework and RESTful Web Service

Source: Internet
Author: User
Tags representational state transfer jboss pojo java

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 that allows Java programmers to use a fixed set of interfaces to develop rest applications, avoiding reliance on the third box

, while Jax-rs uses the Pojo programming model and annotation-based configuration and integrates JAXB to effectively shorten the rest application's development cycle, JSR-311 started at 2007

In February, two final versions of the 1.0,1.1 were released so far, 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 JCP to the Java

Community Process) to mention the JSR, after the Expert group review 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.

target of the Jax-rs API

based on Pojo: This API provides a set of annotations, classes, and interfaces for exposing POJOs to network resources (web Resource) and defining the lifecycle and effective scope of objects; http as the center: 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 defines how the application is deployed in the servlet container and as a JAX-WS provider; into 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 Java The features and components that EE provides.


Below see a relatively good introduction jax-rs and rest of the article, reprinted to study together.

First, Introduction

The Java web has many mature frameworks that can be divided into two types of Web application and Web Services. The framework for Web application includes the official servlet/jsp, JSTL/JSF, and third party struts/spring MVC (action-based). WEB services projects can be divided into xml-based (SOAP/WSDL) and JSON based, Java communitiy defines standards for both approaches, and Java EE5 introduces Jax-ws (Java API for XML Web Services)-jsr224,java EE6 introduced Jax-rs (Java API for RESTful Web Services)-jsr331. RESTful service is becoming more and more popular because of its characteristics of light weight, good testing and elasticity. Jersey,resteasy are the concrete implementations of the JAX-RS standard.

Second, REST

Rest (representational State transfer, presentation Layer status transformation) is a design concept that gradually becomes the mainstream of web design, one of the first by Roy Thomas Fielding (the http1.0/1.1 Protocol's main architect, One of the Apache authors, the first chairman of the Apache Foundation, was presented in a 2000 doctoral thesis. Resource (Resource): An entity on a network (specific information), each resource is identified and positioned with a URI. All resources are located on the server. Presentation layer (Representation): the manifestation of resources. For example, text information can be presented in TXT, or it can be expressed in html,xml,json format, even in binary format. The URI represents only the resource entity, and its representation is specified in the Accept and Content-type fields in the HTTP request header, which is the description of the presentation layer. All the things that the client sees are just the performance layer of the resources on the server, and the client and the server are passing the performance layer (the resource request carries the parameter, returns the Json,txt,jpg and so on Mime-type). State Transfer: All operations of the client are essentially a way to change the state of the resource in the server. The client can only see the performance layer of the resource, so the transformation of the resource state on the server must be based on the performance layer. The only way for clients to change the state of server resources is to use HTTP requests, using different methods of HTTP requests to implement different state changes to the resource (such as adding or deleting the create,read,update,delete). The request methods designed in the HTTP protocol include get (fetch), POST (add), put (update), delete (delete), head,status,options, etc., different methods represent different operations, but HTML only implements get and POST.

example, for example, there is a restful service for book management, and the service will be rendered in the following form (regardless of how the service is specifically implemented):

Resources:
The collection of all books in the system is a resource that can be http://www.example.com/books to indicate that there is a book ID of 1000 in the system, this book is also a resource, you can use the URL http:// www.example.com/books/1000 to say
Operation:
If you want to see what specific books are contained in a book set, you can use the Get method to request a collection resource:
Get Http://www.example.com/books
Get http://www.example.com/books/1000 If you want to add a new book, you can use the Post method to request a collection resource (automatically generate an ID of 1001 if successful):
POST http://www.example.com/books { {' name ': ' Good Book '}, {' Price ':}} If you want to modify a book, you can request a resource for the book using the Put method:
Put http://www.example.com/books/1001 {' Price ': 98}}}
DELETE http://www.example.com/books/1000

Special Notes The URI should not contain verbs. An entity that is represented by a resource should all be nouns. A resource action action can only be represented by an HTTP request method.

For example,/POSTS/SHOW/1 should be changed to/POSTS/1 using the Get method to indicate a show operation. Some of the actions that are difficult to express directly by means of the request can be replaced by nouns as a service resource.

For example, the transfer action can be modified to post/transaction from=1&to=2&amout=100.00 the URI should not contain the version number. Different versions are actually different layers of the same resource, and all should use the same URI. The version number is distinguished in the Accept field of the HTTP request header (reference http://www.informit.com/articles/article.aspx?p=1566460).

For example

Http://www.example.com/app/1.0/foo

Http://www.example.com/app/2.0/foo

To differentiate in the request header:

Accept:vnd.example-com.foo+json; version=1.0

Accept:vnd.example-com.foo+json; version=2.0

Third, Jax-rs

Jax-rs, like all Java EE Technologies, provides only technical standards that allow each manufacturer to have its own implementation version: Resteasy (JBoss), Jersey (sun-provided reference implementation), Apache CXF, Restlet ( The first rest frame, preceded by Jax-rs, Apache Wink. Jax-rs is a servlet based on Java EE. The annotations defined in the standard greatly simplify the description of resource locations and parameters, and can encapsulate a Pojo Java class into a Web resource using annotations alone. Jax-rs also has a similar approach to spring dependency injection, reducing the coupling between classes.

A simple RESTful Web service example of the JAX-RS standard, such as a greeter resource with a URI of http://localhost:8080/greeter/

@Path ("/greeter") public   
class Greeterresource {
    @GET
    @Path ('/{name} ') public
    String SayHello (@ Pathparam ("name") String name {return
        "Hello," + Name;
    }
    @DELETE
    @Path ("/{name}") Public
    String Saybye (@PathParam ("name") string name) {return
        "Bye," + name;
}
}

Request the resource using the Get Method (Http://localhost:8080/greeter/tom)

Will get output: Hello, Tom

Request the resource using the Delete method (http://localhost:8080/greeter/lily)

Will get output: Bye, Lily

If you define the above resource class as an interface, separating the definition and implementation of the rest service is a better way to implement it. The code is simpler and clearer, and later revisions are more convenient.

iv. Annotations of Jax-rs 1. Annotation of relative path of resource class or method

@Path

If you want a Java class to be able to handle a rest request, the class must add at least one @path ("/") annotation, and for the method, the annotation is optional and, if not added, the definition of the inherited class.

The value in the Path can be a complex expression, for example, @path ("{ID}"), where {XXX} represents a template parameter, the template parameter is a wildcard character defined in @path, which starts with {The middle is a bunch of letters and numbers of mixed strings (cannot contain/characters), ending with}. Another example: @Path ("{firstname}-{lastname}")

Path also supports regular expressions, such as: @Path ("{ID: \\d+}")

Priority check rules (if such a rule does not solve the problem, that is, the design is too complex): first check the number of matching characters, the more the more preferred; second, check the number of embedded template expressions, the more the more preferred; Last check the number of Non-default template expressions (the default template is the template for an undefined regular expression)

For example/customers/{id}/{name}/address/customers/{id:. +}/address/customers/{id}/address/customers/{id:. +}

The character of path (if the expression in path contains characters that need to be escaped, Jax-rs is automatically escaped; otherwise it is considered as well as the URL Encoding) allow A-Z, A-Z, 0-9 allow _-!. ~ ' () * reserved (to be escaped);: $$+=?/[]@ its characters need to be escaped with%hh

 

A child Resource Locator (Subresource locators), a method that specifies a @path annotation but does not specify a httpmethod annotation, which can return another resource class object that then distributes and processes requests for child resources. A child resource class does not need to be exposed as a service, so it is not necessary to add @path annotations on the class.

@Path ("/customers") public
class Customerresource {
...
@Path ("{database}-db") public
Customerresource getdatabase (@PathParam ("database") String db) {
//Find the I    Nstance based on the DB parameter
customerresource resource = locatecustomerresource (db);
return resource;
}
protected Customerresource Locatecustomerresource (String db) {
...
}
...... } public class Customerresource {@GET @Path (

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.