Simplifying REST application Development with Jax-rs

Source: Internet
Author: User
Tags representational state transfer

This article details the support of JSR-311 (Jax-rs:java API for RESTful Web Services) introduced in Java EE 6, and presents a complete sample application showing Jax-rs key design details as well as the JPA Used in combination.

0 Reviews:

Invar, software engineer, EMC

Zhang Hao, software engineer, EMC

September 07, 2009

    • Content

Develop and deploy your next application on the IBM Bluemix cloud platform.

Get started with your trial

About REST

REST is an abbreviation for the English representational state Transfer, with Chinese translation as "representational status transfer". The term REST is used by Roy Fielding in his doctoral dissertation, architectural Styles and the Design of network-based software architectures . Proposed. REST is not a standard, but an architectural style for developing WEB applications that can be understood as a design pattern. REST is based on Http,uri, as well as the existing widely popular protocols and standards of XML, along with the Rest,http protocol being used more correctly.

Compared to SOAP-and WSDL-based WEB services, REST mode provides a more concise implementation scenario. More and more WEB services are now being designed and implemented in restful style, and the more famous rest services in the real world include: Google AJAX search API, Amazon simple Storage service (Amazon S3), etc.

REST-based WEB services follow some basic design principles:

    • Each object or resource in the system can be addressed through a unique URI structure that is simple, predictable, and easy to understand, such as a URI that defines a directory structure.
    • Explicitly use the HTTP method to establish a one-to-one mapping between the Create, retrieve, update, and delete (Crud:create, Retrieve, updates, and delete) operations and HTTP methods in a manner that follows the protocol defined by RFC-2616:
      • To create resources on the server, you should use the POST method;
      • To retrieve a resource, you should use the GET method;
      • To change the state of a resource or update it, you should use the PUT method;
      • To delete a resource, you should use the Delete method.
    • Each resource accessed by a URI can be represented in a different form (such as XML or JSON), depending on the client accessing the resource, and the client and service provider using a mechanism for content negotiation (request header and MIME type) to select the appropriate data format. Minimize data coupling to each other.

Back to top of page

Jax-rs--Java API for RESTful Web Services

Java EE 6 introduces support for JSR-311. JSR-311 (Jax-rs:java API for RESTful Web Services) is designed to define a unified specification that allows Java programmers to develop REST applications using a fixed set of interfaces, avoiding the reliance on third-party frameworks. At the same time, Jax-rs uses the POJO programming model and label-based configuration and integrates JAXB to effectively shorten the development cycle of REST applications.

The API defined by Jax-rs is located in the Javax.ws.rs package, where some of the main interfaces, annotations, and abstract classes are shown in Figure 1.

Figure 1. Javax.ws.rs Package Overview

Specific implementations of JAX-RS are provided by third parties, such as Sun's reference implementation Jersey, Apache CXF, and JBoss resteasy.

In the next article, we will introduce some key details of Jax-rs to the reader in conjunction with an account book application.

Back to top of page

Introduction to the example

The Bookkeeping sample application contains 3 resources: Accounts, users, and types of accounts, with a one-to-many relationship between the user and the accounts, the type of accounts, and the accounts. Key features of the bookkeeping include:

    1. Record the amount of time a user spends on which category
    2. Query records by user, type of account, time or amount
    3. Management of users and types of accounts

Back to top of page

Resource Classes and Resource methods

WEB resources are implemented as a Resource class, and requests for resources are handled by the Resource method. The Resource class or Resource method is tagged with the path callout, and the value of the path callout is a relative URI path that is used to locate the resource, and the path can contain any regular expression to match the resource. Like most jax-rs callouts, a path callout is inheritable, and a subclass or implementation class can inherit a path callout in a superclass or interface.

The Resource class is POJO, using jax-rs annotations to implement the appropriate WEB resources. The Resource class is divided into the root Resource class and the child Resource class, except that the child Resource class does not have a Path callout on the class. The instance method of the Resource class has the Path callout, or the Resource method or the sub-Resource locator, except that there is no @GET, @POST, @PUT, @DELETE, or custom @HttpMetho on the sub-Resource locator D. Listing 1 shows the root Resource class and its Resource methods used in the sample application.

Listing 1. Root Resource class
@Path ("/") public  class Bookkeepingservice {     ...     @Path ("/person/")     @POST     @Consumes ("Application/json") public     Response Createperson (person person) {         ......     }     @Path ("/person/")     @PUT     @Consumes ("Application/json") public     Response Updateperson (person person) {         ......     }     @Path ("/person/{id:\\d+}/")     @DELETE public     Response Deleteperson (@PathParam ("id")     int id) {         ......     }     @Path ("/person/{id:\\d+}/")     @GET     @Produces ("Application/json") Public person     Readperson (@ Pathparam ("id")     int id) {         ...     }     @Path ("/persons/")     @GET     @Produces ("Application/json") public     person[] Readallpersons () {         ......     }     @Path ("/person/{name}/")     @GET     @Produces ("Application/json") Public person     Readpersonbyname (@ Pathparam ("name")     String name) {         ...  }  ......
Parameter callout

Annotations that involve Resource method parameters in Jax-rs include: @PathParam, @MatrixParam, @QueryParam, @FormParam, @HeaderParam, @CookieParam, @ DefaultValue and @Encoded. The most common of these is @PathParam, which is used to map template variables in @Path to method parameters, template variables support the use of regular expressions, and semicolon-delimited between variable names and regular expressions. For example, for the Bookkeepingservice class shown in Listing 1, if you request a resource "/person/jeffyin" using the Get method, the Readpersonbyname method is called, and the method parameter name is assigned a value of "Jeffyin" And if the resource "/person/123" is requested using the Get method, the Readperson method is called and the method parameter ID is assigned a value of 123. To learn how to use other parameter callouts, refer to the Jax-rs API.

JAX-RS specifies that only one parameter is allowed in the Resource method without any parameter callouts, which are called entity parameters and are used to map the request body. For example, listing 1 shows the Createperson method of the Bookkeepingservice class and the parameter person for the Updateperson method.

Parameters and return value types

The Resource method's valid parameter types include:

    1. Native type
    2. The constructor receives either a single string parameter or any type that contains a static method valueOf that receives a single string argument
    3. List<t>,set<t>,sortedset<t> (T is the 2 types above)
    4. Entity parameters used to map the request body

The Resource method's valid return value types are:

    1. void: Status code 204 and empty response body
    2. The Status property of the Response:response specifies the state code, and the Entity property is mapped to the response body
    3. The Entity property of the genericentity:genericentity is mapped to the response body, the Entity property is empty, the status code is 204, and the non-empty state code is 200.
    4. Other types: The returned object instance is mapped to the response body, the instance is empty, the status code is 204, the non-empty state code is 200

For error handling, the Resource method can throw an uncontrolled exception webapplicationexception or return a Response object that contains the appropriate set of error codes.

Context Callout

With context annotations, instance fields of the root Resource class can be injected into the following types of context resources:

    1. Request, Uriinfo, Httpheaders, Providers, SecurityContext
    2. HttpServletRequest, HttpServletResponse, ServletContext, ServletConfig

To learn how to use the 1th type of context resource, refer to the Jax-rs API.

Back to top of page

CRUD operations

Jax-rs defines @POST, @GET, @PUT, and @DELETE, respectively, corresponding to 4 HTTP methods for creating, retrieving, updating, and deleting resources.

POST Callout

The POST callout is used to create resources on the server, as shown in Listing 2.

Listing 2. POST Callout
@Path ("/") public  class Bookkeepingservice {     ...     @Path ("/account/")     @POST     @Consumes ("Application/json") public     Response CreateAccount {         ......     }  ......

If the resource "/account" is requested using the POST method, the CreateAccount method is called, and the JSON-formatted request body is automatically mapped to the entity parameter account.

GET Callout

The GET label is used to retrieve resources on the server, as shown in Listing 3.

Listing 3. GET Callout
@Path ("/") public  class Bookkeepingservice {     ...     @Path ("/person/{id}/accounts/")     @GET     @Produces ("Application/json") public     account[] Readaccountsbyperson (@PathParam ("id")     int id) {         ...     }     ......     @Path ("/accounts/{begindate:\\d{4}-\\d{2}-\\d{2}},{enddate:\\d{4}-\\d{2}-\\d{2}}/")     @GET     @Produces (" Application/json ") public     account[] Readaccountsbydatebetween (@PathParam (" Begindate ")     String begindate, @PathParam ("EndDate")     String endDate) throws ParseException {         ...     }  ......

If the resource "/person/123/accounts" is requested using the GET method, the Readaccountsbyperson method is called, and the return value of the method parameter ID is assigned to the 123,account array type is automatically mapped to the JSON-formatted response body And if the resource "/accounts/2008-01-01,2009-01-01" is requested using the GET method, the Readaccountsbydatebetween method is called, and the method parameter begindate is assigned the value "2008-01-01 ", EndDate is assigned the value" 2009-01-01 ", and the return value of the account array type is automatically mapped to the JSON-formatted response body.

PUT Callout

The PUT callout is used to update resources on the server, as shown in Listing 4.

Listing 4. PUT Callout
@Path ("/") public  class Bookkeepingservice {     ...     @Path ("/account/")     @PUT     @Consumes ("Application/json") public     Response Updateaccount         ......     }  ......

If you request a resource "/account" using the PUT method, the Updateaccount method is called, and the JSON-formatted request body is automatically mapped to the entity parameter account.

DELETE Callout

The delete callout is used to delete resources on the server, as shown in Listing 5.

Listing 5. DELETE Callout
@Path ("/") public  class Bookkeepingservice {     ...     @Path ("/account/{id:\\d+}/")     @DELETE public     Response DeleteAccount (@PathParam ("id")     int id) {         ......     }  ......

If the resource "/account/323" is requested using the DELETE method, the DeleteAccount method is called and the method parameter ID is assigned a value of 323.

Back to top of page

Content negotiation and data binding

Web resources can have different representations, and a mechanism called content negotiation is required between the server and the client: as a server, the produces annotation of the Resource method is used to specify the data format (MIME type) of the response body. The consumes callout is used to specify the data format of the request body, and as a client, the Accept request header is used to select the data format of the response body, and the Content-type request header is used to identify the data format of the request body.

Jax-rs relies on implementations of Messagebodyreader and Messagebodywriter to automate the serialization of return values to the response body and the deserialization of the request body to the entity parameters, where the request/response data in XML format is associated with the Java Automatic binding of an object depends on the implementation of JAXB.

Users can use Provider annotations to register with custom Messagebodyprovider, as shown in Listing 6, Gsonprovider class uses Google Gson as a JSON-formatted Messagebodyprovider implementation 。

Listing 6. Gsonprovider
 @Provider @Produces ("Application/json") @Consumes ("Application/json") public class Gsonprovider implements Messagebod     Ywriter<object&gt, messagebodyreader<object> {private final Gson Gson;                 Public Gsonprovider () {Gson = new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Setdateformat (     "Yyyy-mm-dd"). Create (); } public boolean isreadable (class<?> type, type GenericType, annotation[] annotations, mediatype Med     Iatype) {return true; Public Object Readfrom (class<object> type, type GenericType, annotation[] annotations, mediatype m Ediatype, multivaluedmap<string, string> httpheaders, InputStream entitystream) throws IOExc     Eption, Webapplicationexception {return Gson.fromjson (new InputStreamReader (Entitystream, "UTF-8"), type);            } public boolean iswriteable (class<?> type, type GenericType, annotation[] annotations, MediaType mediatype) {return true; } public long GetSize (Object obj, class<?> type, type GenericType, annotation[] annotations, Mediaty     PE mediatype) {return-1; } public void WriteTo (Object obj, class<?> type, type GenericType, annotation[] annotations, Mediaty PE mediatype, multivaluedmap<string, Object> httpheaders, OutputStream Entitystream) throws     IOException, webapplicationexception {entitystream.write (Gson.tojson (obj, type). GetBytes ("UTF-8")); }  }

Back to top of page

Jax-rs combined with JPA

Because Jax-rs and JPA also use POJO and callout-based programming models, they are easy to use together. Web Resources in the sample app, such as accounts, are also persisted to entities in the database, with JAXB annotations on the same POJO class, and JPA annotations (or Gson annotations), which reduces the number of classes in the application. As shown in Listing 7, the account class can be reused between Jax-rs and JPA, which can be jax-rs bound to the Xml/json data of the request body/response body, or it can be persisted to the relational database by JPA.

Listing 7. Account
@Entity  @Table (name = "Table_account")  @XmlRootElement Public  class Account {     @Id     @ Generatedvalue (strategy = generationtype.identity)     @Column (name = "col_id")     @Expose     private int ID;     @ManyToOne     @JoinColumn (name = "Col_person")     @Expose     private person person;     @Column (name = "Col_amount")     @Expose     private BigDecimal AMOUNT;     @Column (name = "Col_date")     @Expose     private date date;     @ManyToOne     @JoinColumn (name = "Col_category")     @Expose     Private category category;     @Column (name = "Col_comment")     @Expose     private String COMMENT;  ......

Back to top of page

Conclusion

As a lightweight Web services architecture, Rest is adopted by more and more developers, and Jax-rs's release regulates the interface of rest application development. In this paper, we first describe the basic design principles of REST architecture, and then, through an example application, show how JAX-RS can achieve the above design principles through various annotations, and finally introduce the combination of Jax-rs with JPA and Gson. The sample application in this article uses Jersey and OpenJPA, deployed on Tomcat containers and replaced with other implementations that only need to modify the Web. XML and Persistence.xml configuration files.

Back to top of page

Download
Description name size
The sample code for this article Bookkeeping.zip KB
Resources
    • Write Rest Service (developerworks,2007 November): This tutorial discusses the concepts of the rest and Atom Release Protocol (Atom Publishing Protocol,app) and shows how to apply it in a service.
    • Building RESTful Web Services (developerworks,2008 August): This tutorial starts with the basic concepts of REST and walks you through building applications using the Restlet framework.
    • "Rest-based WEB services: Fundamentals" (developerworks,2008 December): In this article, Alex Rodriguez will introduce you to the fundamentals of rest.
    • "JSR 311", a specification document for JSR 311.
    • "Jax-rs API", Jax-rs API documentation.
    • "Jersey", the reference realization of JAX-RS.
    • Apache CXF, a top-level project under the Apache Software Foundation, provides an open source implementation of Jax-WS, Jax-rs, and more.
    • "Google Gson", an open-source class library for bidirectional conversion of Java objects to JSON-formatted data, based on Apache License 2.0.
    • "Apache OpenJPA", a top-level project under the Apache Software Foundation, provides an open source implementation of the JPA specification.
    • Java Technology Zone: find technical articles on all aspects of Java programming.

Transferred from: http://www.ibm.com/developerworks/cn/java/j-lo-jaxrs/

Simplifying REST application Development with Jax-rs

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.