Using Jersey to create RESTful services with POJOs

All code for this example is available on GitHub at https://github.com/craigew.

This post will provide some examples of how to use the Jersey framework with POJO support. All the methods, barring the first example method, will consume and/or produce JSON in the request and response. I have provided examples for each of the most common verbs, namely:

  • GET – will provide a list based on the URI.
  • POST – will create a new entry.
  • PUT – will replace/update an entry based on the URI.
  • DELETE – will delete a entry based on the URI.

So first off I added my dependencies to my POM. As always my dependencies are managed using Maven.


<dependencies>
   <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-server</artifactId>
     <version>1.17</version>
   </dependency>
   <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-json</artifactId>
     <version>1.17</version>
   </dependency>
   <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-client</artifactId>
     <version>1.17</version>
   </dependency>
   <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-servlet</artifactId>
     <version>1.17</version>
   </dependency>
</dependencies>

Next I want to package this as a war, so I added the following to the POM file.


   <packaging>war</packaging>
   <build>
     <plugins>
       <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-war-plugin</artifactId>
          <configuration>
            <webXml>web\WEB-INF\web.xml</webXml>
          </configuration>
      </plugin>
     </plugins>
   </build>

I am deploying this example to Tomcat by simply copying the built war into the webapps folder of my Tomcat install. For some reason I could not run the example straight from my IDE, IntelliJ. For some reason it was not deploying the required dependencies when running or debugging from IntelliJ. That is something to have a look at, when I have got time.

The final configuration to do is in the web.xml file.

The config below tells the Jersey API where my annotated classes are that it needs to listen for.

<init-param>
   <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.craigew.rest</param-value>
</init-param>

The next config tells Jersey that I am wanting to use it’s POJO mapping features.

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

Finally you tell jersey servlet to intercept all request with url pattern of /api/*.

<servlet-mapping>
    <servlet-name>JerseyAPI</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

Now we can start coding. The first method I create does not utilise the Jersey POJO mapping features. I simply manually create a JSON response for a very basic “Hello World” example.


@Path("/person")
public class PersonApi {

   @Path("/greet")
   @GET
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(MediaType.APPLICATION_JSON)
    public JSONObject sayHello() {
      try {
         return new JSONObject().put("greeting", "Hello world");
      } catch (JSONException e) {
         return null;
      }

    }

}

So the URI for this example would look something like:

…/api/person/greet

And it simply returns a JSON object with a string containing “Hello World”.

The next example I take a parameter from the path {name}.


@Path("/greet/{name}")
 @GET
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
public PersonResponse sayHelloToSomeone(@PathParam("name") String name){
      PersonResponse personResponse =new PersonResponse();
      personResponse.setResponse("Hello " + name);
      return personResponse;
 }

Now we have started to use the Jersey POJO mapping features. In this code snippet we are returning a POJO object that Jersey then serialises into JSON for us.

So the URI for the above call would look something like:

…/api/person/greet/craig

And the service will then return JSON looking like the below snippet:

 {
   response: "Hello craig"
 }

The final example I will write about is when we are passing a JSON string via the Payload. Jersey then deserialises the JSON into our POJO, allowing us to easily work with the object in Java.


package com.craigew.model;

public class Person {
private String name;
private String surname;

public Person() {}

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
   }

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }
}

First thing to note is that the empty constructor is required by the parser to initially create the object. The getters and setters I found where also necessary. Simply making the attributes public did not work.

In the example below I simulate creating a new person.


@Path("/create")
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public PersonResponse createAPerson(Person person){
    System.out.println("Creating a person");
    PersonResponse personResponse =new PersonResponse();
    personResponse.setResponse(person.getName() + " " + person.getSurname() + "        added to the database");
    return personResponse;
 }

The URI for the above code example would look like:

…/api/person/create

With the following JSON in the payload of the POST request.

{“name” : “Craig”, “surname” : “Williams”}

The nice thing about writing your RESTful service like this is that you can directly unit test them using JUnit.

@Test
public void should_create_a_person(){
  Person person=new Person();
  person.setName("Craig");
  person.setSurname("Williams");
  Assert.assertEquals("Craig Williams added to the database",new     PersonApi().createAPerson(person).getResponse());
 }

Although this is a very superficial example of unit testing it allows you to remove the infrastructure while developing and you can then practice TDD properly, by first writing your tests and then implementing your methods.

For manually testing RESTful services, including the infrastructure, I use a Chrome plugin called, Advanced Rest client. It is by far the best client I have used while developing RESTful services.

Advertisements

About craigew

I am a technologist at heart and enjoy working with like minded people who show a passion for what they do. Craftsmanship is important to me and each day I am honing my skills as a software developer on a journey to one day becoming a master software craftsman.
This entry was posted in Example code, Software development and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Using Jersey to create RESTful services with POJOs

  1. Pingback: openjpa-tutorials | mauroprogram's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s