automation-1 automation-2 automation-3 automation-4 consultancy-1 consultancy-2 consultancy-3 consultancy-4 facebook google-plus outsourcing-1 outsourcing-2 outsourcing-3 outsourcing-4 power-engineering-1 power-engineering-2 power-engineering-3 power-engineering-4 twitter

Jersey in GWT web application

Jersey is a fremework for creating RESTful services according to JAX RS api. JAX RS itself is only specification of the interface, while Jersey is implementation.

In simple words, Jersey allows easy creation of REST services. This means that services are created as normal Java objectes, while Jersey handles HTTP verbs (GET, PUT, POST…) and conversion from Java objects to JSON (or other respresentations). No special knowledge is needed for basic service which can be made with 5-minutes tutorial, however, Jersey provides many advanced fetures for advanced users.

Below is a quick&dirty tutorial I have composed for internal use. It does not pretend to give you full knowledge of Jersey, just a quick intro into functional application. Goal of the tutorial is to create a simple REST service that resides in the web server. When accessed via browser, service will return JSON formated data of the Java class.

The tutoral uses material from Javaforge , with additional instructions on setting up a project and is based on GWT web application project type. For sure it could be used with other project types – we are using GWT for our development. Steps for installing GWT in Eclipse can be found on the following link.

1. Setup a new project

We will need a server application which is accessed via web browser – so “Web application” project type is our friend. Create an empty project, there is no need for Google App Engine support. As package name, you can put whatever you prefer or put rs.iten if you want to directly copy-paste code below.

2. Setup libraries for a project

Jersey libraries are mandatory, but it is not one library – there is a whole bunch of .jar files, in three directories. The easiest is to add all libraries from all directories (api, ext and lib).

Next step is to copy libraries to the web server library directory. Just copy all .jar files into war/WEB-INF/lib directory of your project. Note that you don’t need to separate .jar files into separate directories, just copy all .jar files into single destination directory.

One more library is needed – genson lib. Genson is a library for conversion between Java and JSON objects and vice versa. Jersey itself contains library for this conversion, however, we faced a problems with Java arrays and switched to Genson. So far it work perfectly and is trivial to install – just put it into lib directory, it works out of the box.

3. Add some code

Jersey is designed to use Java objects and to seamleslly convert them to JSON. You don’t need to understand in details how HTTP verbs work or how Java <–> JSON conversion is done.

For the purpose of this example, we will create Person class. This class will have some basic attributes and will be used for data exchange between server and client.

package rs.iten.shared;

import java.util.Date;

public class Person {
    private int id;
    private String name;
    private Date dateOfBirth;

    public Person() { }

    public Person(int id, String name, Date dateOfBirth) {
        this.setId(id);
        this.setName(name);
        this.setDateOfBirth(dateOfBirth);
    }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public Date getDateOfBirth() { return dateOfBirth; }
    public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

Now let’s add some server code that will return some instances of Person class:

package rs.iten.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import rs.iten.shared.Person;

@Path("/person")
public class PersonResource {
    private static int counter = 1;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getPersons() {
        List<Person> persons = new ArrayList<Person>();
        for (int i = 0; i < 5; i++) {
            persons.add(new Person(counter, "name-" + counter, new Date()));
            counter++;
        }
        
        return persons;
    }
}

The code above is the key componenet of Jersey REST service. It is possible to write regular Java code, without any reference to web services or media type representation. Adding annotations is what transforms this Java code into web services.

@Path is annotation that maps this class into /person path in server. Accessing /person from browser means accessing this class.

@GET is annotation that denotes method getPersons​ as a method that will be called on HTTP GET verb.

@Produces(MediaType.APPLICATION_JSON) means that the return type of the function will be converted to JSON

Application flow is the following: browser issues GET request on a path /Person. Server will know that class PersonResource handles /Person path. Method for GET request is getPersons, whose return type is automatically converted to JSON and returned to browser.

4. Configure server

Server is configured through web.xml file found in war/WEB-INF directory. Replace default <servlet> and <servlet-mapping> elements with the following:

<servlet>
    <servlet-name>rest-test</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>rs.iten.server</param-value>
    </init-param>
    <init-param>
      <param-name>jersey.config.server.tracing</param-name>
      <param-value>ALL</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>rest-test</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping> 

The above configuration means that web server will load Jersey servlet container, specified with <servlet-class> element and will seek for particular interfaces within rs.iten.server package. Our test class, PersonResource, resides in this location.

The <servlet-mapping> element contains path that will be used in browser for accessing servlet configured in the above step.

5. Remove unneeded code – not mandatory

Web application created by GWT plugin has full capabilities for both server and client development. Considering that we are only creting REST interface on the server, client features are not needed – but you can keep them, they will not affect our REST interface. Defualt web application will be visible in browser, but will not be functional – generated servlet (GreetingServiceImpl.java) is removed from web.xml and thus not available.

6. Test application

Run application as a normal GWT web application. In web browser, type the following address:

localhost:8888/rest/person

Your web service is up and running and will return person’s data in JSON format :) Service is accessible via any device that is capable of HTTP request. Integration with GWT application can be done either by using Java HTTP request classes or via some library like RestyGWT.

Share this article additional message.