Jersey HTTP GET Example

In this blog post I am going to share with you how to handle HTTP GET request in your Java Web Service created with Jersey framework and how to response back with XML or JSON Response.

If you do not have your Java RESTful Web Service created yet please follow the below link to a very simple tutorial which will help you set up a new Jersey Application in few minutes.

Once you have your Jersey JAX-RS app created, open it in your favourite Java Development Environment like for example Netbeans and lets start creating our very first Web Service End Point.

  1. In your src/main/java folder let’s create a new package called com.appsdeveloperblog.api . So your folder structure will look like this: src/main/java/com/appsdeveloperblog/api
  2. Inside of com.appsdeveloperblog.api let’s create a new file called MyApi.java. A complete path to your MyApi.java file within the project will be src/main/java/com/appsdeveloperblog/api/MyApi.java
  3. Open MyApi.java file and right above the class name add the following annotation: @ApplicationPath(“api”) This will mark your application main path and will serve as the base URI for all resource URIs. Any HTTP request you will send will need to be sent to an URI that begins with /api.  You can give it any name “api” or “myapi” or “app-api” but keep it short and simple since it is going to be part of your every URI.  There is no other changes we need to make to this class at this moment let’s leave it as is. So your MyApi.java should like like the one below:
package com.appsdeveloperblog.api;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("api")
public class MyApi extends Application 
{

}

Now let’s create the response class with which our Web Service will respond when HTTP Get method is called.

Creating Java Model to Be Returned in Response

Let’s say user calls HTTP GET method of our web service which will need to return a list of user profiles. Thus user Profile will need be an object that we need to return and because there might be more than one profile we will return a collection of Profile objects. Let’s create Profile class.

  1. Create a new package called com.appsdeveloperblog.api.response.model. We will keep all objects with which our web service can respond in a new package.
  2. Create a new class with a name Profile. Like the one I have below:
package com.appsdeveloperblog.api.response.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Profile {
    private String firstName;
    private String lastName;
    
    public Profile()
    {
        
    }
    
    public Profile(String firstName, String lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

There are couple of very important things to note here:

  1. Profile class needs to be a Plain Old Java Object or POJO,
  2. Profile class needs to be annotated with @XmlRootElement,
  3. Profile class should have a no args constructor.

Now when we have Profile class created let’s create the Web Service Root Resource class.

Creating Web Service Resource Class

Web Service Resource class is a simple Java class which contains a few important Jersey framework annotations. These annotations will help Jersey identify which java methods should be triggered when HTTP GET or HTTP POST request was sent at a specified URI. For example we can mark a specific method with a special Jersey annotation which will make it triggered when user sends HTTP GET request to /api/users URI. Let’s looks at the below example:

  1. Create a new java package called com.appsdeveloperblog.api.resources,
  2. Inside of rest com.appsdeveloperblog.api.resources package let’s create a new java class called UserEntryPoint.java,
  3. Right above the class name let’s add a new Jersey [email protected] with a value of /users, like so: @Path(“/users”), 
  4. Inside of this UserEntryPoint class create only one method called getProfiles() like in the code example below which marks this method with another annotation @GET right above the method name,
  5. Add @Produces annotation above the method name as well. We will make the geProfiles() method be able to return information either in XML or JSON format depending on which one of these the calling client application can support. So your UserEntryPoint.java file should look like the one I have below:
package com.appsdeveloperblog.api.resources;

import com.appsdeveloperblog.api.response.model.Profile;
import java.util.ArrayList;
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;
 
@Path("/users")
public class UserEntryPoint {

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Profile> getProfiles() {
        
        ArrayList<Profile> names = new ArrayList();
        names.add(new Profile("Jone", "Jones")); 
        names.add(new Profile("James","Bond"));
       
        return names;
    }

}

Before we run and and see how this example works you can compare our other files:

My pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.appsdeveloperblog.api</groupId>
    <artifactId>AppAPI</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>AppAPI Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.bundles/jaxrs-ri -->
        <dependency>
            <groupId>org.glassfish.jersey.bundles</groupId>
            <artifactId>jaxrs-ri</artifactId>
            <version>2.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.25</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>AppAPI</finalName>
    </build>
</project>

My web.xml file

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

My context.xml file

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/AppAPI"/>

If everything is ok, we can now build and run this project. Once the web application file, which is in my case going to be called AppAPI.war, is deployed to Apache Tomcat we can open in the browser window url:  http://localhost:8080/AppAPI/api/users

where

localhost:8080 is the domain name and Apache Tomcat port number,

/AppAPI is the context of our web app which is specified in context.xml file

/api is the value specified in our MyApi.java file

/users is the Root Resource Path which is specified in UserEntryPoint.java right above the class name with the @Path annotation

If everything is ok, we should get back a response in XML format like the one below:

<profiles>
   <profile>
     <firstName>Jone</firstName>
     <lastName>Jones</lastName>
   </profile>
  <profile>
     <firstName>James</firstName>
     <lastName>Bond</lastName>
  </profile>
</profiles>

Note:

  • If you do not want to support XML format and want to return JSON instead, then remove the MediaType.APPLICATION_XML from your @Produces annotation
  • If you do not want to see the “AppAPI” in your URI simply rename it to something else in context.xml file of your project or completely remote it from there. To get rid of AppAPI from your URI your context.xml file should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path=""/>

If something is not working for you and you would like to compare my project with yours, below is the link to my entire project:

Source Code

Download source code of this example

I hope this blog post was of some value to you. If you are interested to learn more about building RESTful web services with Java, check out the below video courses which might help you learn and progress much faster than if you google internet for little code examples here and there 🙂 .

 

Java Web Services. Video Course.

Learn how to design,create , consume and secure SOAP and REST web services from scratch in easy steps.

Java
icon

Java Web Services Part 2. Video Course.

Master advanced web services concepts and implement them in easy steps

Java Web Services Part 2
icon

REST Java Web Services. Video Course.

A guide to understanding, accessing, and writing a REST Java web service using Apache and Java EE.

Java Web Services Part 2
icon