Home Application-development Developing RESTful Web Services with Jersey 2.0

Developing RESTful Web Services with Jersey 2.0

By Sunil Gulabani
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book

JAX-RS 2.0 is an enhanced framework based on RESTful architecture. It provides support for both the client and the server. Jersey 2.0 is the reference implementation of JAX-RS 2.0 (JSR 339 specification). This framework has undergone major revisions. The enhanced framework helps developers to use a low-level and simplified API.

This practical, hands-on guide will help you to create RESTful web services easily with individual aspects of the application requests. It will enable you to learn and implement RESTful web services using the new features included in JAX-RS 2.0. It’s a jump start for those who want to try their hand at the new API. It aims to provide practical knowledge of the API along with detailed understanding.

This book covers the new features of JAX-RS 2.0. It covers the complete lifecycle of a web service, that is, from server side to client side. The book focuses on the server API and the client API.

You will learn how to use the server API in order to create web services that will be deployed on the server. This has all different implementations of HTTP methods and media representations. You will also get acquainted with the client API which specifies how to consume the deployed application’s web services. This includes how to handle different HTTP methods and media representations in response to the web services.

You will also get to know Server Sent Events (SSE), which the server uses to push the data event directly to the client. The book will finally take you through the WADL specification. By the end of the book, you will be well equipped to implement Jersey 2.0 and JAX-RS.

Publication date:
November 2013
Publisher
Packt
Pages
98
ISBN
9781783288298

 

Chapter 1. Getting Started

This chapter provides readers with a brief introduction on JAX-RS 2.0. It also includes the principles required to be followed in RESTful web services and the new features that have been introduced in JAX-RS 2.0, such as client API, filters and interceptors, client-side and server-side asynchronous. It also contains some other prominent features, such as listing of modules and dependencies that are used for implementing JAX-RS 2.0. Besides the previously mentioned features, it also provides a demonstration of JAX-RS 2.0 with examples.

 

What is JAX-RS 2.0?


JAX-RS 2.0 is a framework that helps you in writing the RESTful web services on the client side as well as on the server side. Jersey 2.0 is the reference implementation of the JAX-RS 2.0 (JSR 339 specification). Along with the enhancements in Java EE 7, JAX-RS 2.0 has also been revised dramatically.

The following is a list of the RESTful principles that must be followed:

  • An ID should be assigned to everything

  • Things should be linked together

  • A common set of methods must be used

  • Multiple representations should be allowed

  • Stateless communication must be kept

Before moving ahead, let's look at the existing features of JAX-RS 1.0:

  • POJO-based Resource API

  • Provides access to the resource classes using HTTP

  • Format (content types) independence

  • Container (web server) independence

  • Inclusion in Java EE

Features of JAX-RS 2.0

JAX-RS 2.0 remains consistent with the central theme of Java EE 7, but it contains other long-awaited APIs too. These APIs are mostly focused around what is referred to as Simplified API. They can be categorized as follows:

Client API

The specifications in the earlier versions of JAX-RS were only accountable for a server-side API for the RESTful calls. However, the same resulted into the development of different implementers of the server API, that is, Jersey and RESTEasy. This led to the independent development of a client-side API. Now, JAX-RS 2.0 has a Client API that provides support to the server-side specification. This feature is a major incorporation of the previous version of the Jersey Client API. This can be summarized as:

  • Low-level HTTP Client APIs

  • Shared APIs with Server APIs

  • Compatible with some JAX-RS 1.0 implementations

Filters and interceptors

This JAX-RS 2.0 specification is accountable for the client and server filters. In the case of the Client API, implementers provided their own versions of these filters for the client and server. This JAX-RS 2.0 specification, however, absorbs the same into its API. Things that can be done through this specification are:

  • Customization of JAX-RS implementations through well-defined extension points

  • Logging, Compression, Security, and so on can be achieved

  • Shared APIs with Server APIs

  • Compatibility with some JAX-RS 1.0 implementations using some different semantics can be achieved

Client-side and Server-side Asynchronous

This feature allows a request to be dispatched in a nonblocking manner, while the results are made available asynchronously. Also, long-running requests on the server side that are I/O bound can be dispatched. This releases the application server thread and enables it to service other requests. It helps in accomplishing the following tasks:

  • Allows free running of different threads at the server side

  • Request threads can be suspended and resumed as per the need

  • Servlet 3 async support

  • Provides Client API support

Improved Connection Negotiation

This feature helps in automatically determining the response type even if client specification is already present.

Validation

This feature consists of:

  • Services-enabled data validation

  • Bean Validation

  • Inline-constraint annotations on:

    • Fields and properties

    • Request parameters

    • Methods based on response entity

    • Resource classes, that is, path validation using regular expressions

HyperMedia as the Engine of Application State (HATEOAS)

This feature is an important aspect of the RESTful architecture. HATEOAS allows us to provide hyperlinks/URIs in the request/response of the web services. This can be compared with the hyperlinks in an HTML form.

However, Jersey 2.0 can be deployed on several web containers that support Servlet 2.5 or higher, Grizzly 2 HTTP server (which is also the default server for testing), and OSGi containers. For the new async feature of JAX-RS 2.0, Server-Side Events (SSE), we need containers supporting Servlet 3.0.

 

Ease of using and reusing JAX-RS artifacts


As a part of Java EE 7, it is easy to create RESTful web services using JAX-RS 2.0. Using JAX-RS annotations, we can map the POJO resource class to the URIs and the URI templates. Using annotations, it becomes easier to develop web services. Different @*Param annotations are available to access the values of the user request:

  • @PathParam

  • @QueryParam

  • @MatrixParam

  • @HeaderParam

  • @CookieParam

  • @FormParam

  • @DefaultValue

  • @Context

JAX-RS also supports all the Java data types to be supplied in the @*Param annotations. There are other APIs available to create the RESTful web services, but mostly they require more coding. However, in the Jersey implementation of JAX-RS, it is simpler and easier to create the RESTful web services. JAX-RS manages to encode and decode the request/response content according to the media type it mentioned.

 

Modules and dependencies


To provide backward compatibility, all Jersey applications are compiled with Java SE 6. Thus, we can run our Jersey application on Java SE 6 easily though JAX-RS 2.0 is part of Java EE 7.

To create Jersey-based applications, we require several dependencies and for other modules, we require third-party dependencies. Jersey dependencies are loosely-coupled and separated according to the module dependencies. Jersey dependencies are lightweight, so our application has much complexity for dependencies and creation of the RESTful web services.

The following are the core Jersey modules:

  • Jersey Core

  • jersey-client

  • jersey-common

  • jersey-server

Note

You can download the Jersey Core JAX-RS 2.0 Bundle from:

http://repo1.maven.org/maven2/org/glassfish/jersey/bundles/jaxrs-ri/2.0/jaxrs-ri-2.0.zip

Apart from these dependencies, there are Jersey Containers, Connectors, Media, Extensions, Test Framework, and Glassfish Bundles. These dependencies can be easily plugged. You can find Jersey 2.0 binaries on the Jersey 2.0 Maven repository,

http://repo1.maven.org/maven2/org/glassfish/jersey/,

and on

https://maven.java.net/content/repositories/releases/org/glassfish/jersey/.

 

Creating a new project


The first step for creating a new project is to accumulate the required tools:

  • Java JDK (Version 6 or higher)

  • Eclipse IDE (Juno)

  • Apache Tomcat Server (Version 7) or Glassfish Server (Version 4.0)

  • Jersey Framework

Firstly, we will create a web project using Eclipse IDE. Go to File | New | Others | Dynamic Web Project. Follow the steps, and after the project is created, add the following libraries into the classpath:

  • asm-all-repackaged-2.2.0-b14.jar

  • cglib-2.2.0-b14.jar

  • guava-14.0.1.jar

  • hk2-api-2.2.0-b14.jar

  • hk2-locator-2.2.0-b14.jar

  • hk2-utils-2.2.0-b14.jar

  • javax.annotation-api-1.2.jar

  • javax.inject-2.2.0-b14.jar

  • javax.ws.rs-api-2.0.jar

  • jersey-client-2.2.jar

  • jersey-common-2.2.jar

  • jersey-container-servlet-core-2.2.jar

  • jersey-server-2.2.jar

  • osgi-resource-locator-1.0.1.jar

  • validation-api-1.1.0.Final.jar

Now, we need to configure web.xml to the bound Jersey Container with the resources packages:

...........
<servlet>
  <servlet-name>simpleJerseyExample</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>com.demo</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>simpleJerseyExample</servlet-name>
  <url-pattern>/services/*</url-pattern>
</servlet-mapping>
...........

A servlet container is treated as a controller to redirect the specified resource that is being called. jersey.config.server.provider.packages maps the resources that are available in the com.demo package. So, whenever any resource is being requested, ServletContainer checks into the com.demo package for the resource URI and serves the request accordingly.

The next step is to create the Resource class that contains the business logic:

package com.demo;

import javax.ws.rs.Path;
import javax.ws.rs.Get;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Produces;

/**
*    helloWorld Root Resource
*/
@Path("helloWorld")
public class HelloWorldResource{

  @GET
  @PRODUCES(MediaType.TEXT_PLAIN)
  public String greet(){
    return "Hello World!!!";
  }
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

A JAX-RS resource is an annotated POJO, which provides the so-called resource methods that are able to handle the HTTP requests for the URI paths bound to the resource. In the previous code, "helloWorld" is the resource URI:

@Path("helloWorld")

To run the application, create a WAR file and deploy it on the Apache Tomcat Server. Once the project is deployed on the Tomcat server, we are ready to consume the "helloWorld" web service. We can type the resource URL in the browser or we can use curl:

$curl http://localhost:8080/projectName/services/helloWorld
Hello World!!!
 

Summary


We have covered a brief introduction about the JAX-RS 2.0 and Jersey 2.0 features that have enriched the JAX-RS web services. We've analyzed a simple RESTful web service example that shows the basic implementation of the JAX-RS 2.0. In the next chapter, we will see how to use the Server API with different examples of complete sets of code to implement the Server-side web services.

About the Author
  • Sunil Gulabani

    Sunil Gulabani is a software engineer based in India. He is currently working on Java EE and the AWS Cloud platform. He is also a cloud evangelist who helps IT folks to leverage the AWS cloud platform for their business needs. He has insightful knowledge on designing microservices, system architecture and integration, data modeling, relational databases, and NoSQL in order for an application to achieve high throughput.

    He has authored the following books:

    • Developing RESTFul Web Services with Jersey 2.0
    • Amazon S3 Essentials
    • Practical Amazon EC2, SQS, Kinesis, and S3

    Browse publications by this author
Latest Reviews (1 reviews total)
Great Value, top authors!
Developing RESTful Web Services with Jersey 2.0
Unlock this book and the full library FREE for 7 days
Start now