Jersey RESTFul Quick Start Example

0

In this article, we will see how to get started building RESTful services using Jersey.

Jersey is the reference implementation of Sun’s Java API for RESTful Web Services (JAX-RS).

Steps for setup are:

  1. Install latest JDK
  2. We will use Maven as our build tool. If you are new to creating maven project, read here for more details.
  3. Eclipse as the IDE. Read here to know how use Maven to setup web application project in Eclipse.
  4. We will use Jersey 2.22.1 as the JAX-RS implementation
  5. Other than Jersey you also need a web container. We will use Tomcat for our example.

Create Maven RESTFul Project from Command Line

Once you have setup Maven, run the following command to create new Jersey project. This will create a web application project that can be packaged as WAR and deployed in a servlet container. If you note archetypeArtifactId is set to jersey-quickstart-webapp which is a jersey provided maven archetype for creating JavaEE web application that can be deployed on any servlet container supporting Servlet 2.5 and higher.

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeGroupId=org.glassfish.jersey.archetypes 
-DinteractiveMode=false -DgroupId=com.javarticles.rest -DartifactId=RESTFulExample -DarchetypeVersion=2.22.1

Create Maven RESTFul Project in Eclipse

Click on File->New->Other->Maven->Maven Project. The project creation wizard will open up.
Select Jersey provided archetype ‘jersey-quickstart-webapp’ with groupId ‘org.glassfish.jersey.archetypes’.

EclipseSelectFilter_jersey-quickstart-webapp

Select jersey-quickstart-webapp Archetype

Click on next and enter project’s group Id and artifactId.

Enter GroupId/ArtifactId

Enter GroupId/ArtifactId

Project Structure

Name specified in artifactId will be used to create the project folder. In our case, ‘RESTFulHelloWorld’. The project structure created will be according to the Maven convention.

Here is the project project structure.  This is the standard layout for all Maven projects.

Maven RESTFul Project Structure

Maven RESTFul Project Structure

Dependencies

We want to run our RESTFul service on a Servlet container that supports Servlet API 2.5 or above. Jersey uses its own ServletContainer implementation of Servlet and Servlet Filter API to integrate with Servlet containers. Add artifactId jersey-container-servlet-core (of groupId: org.glassfish.jersey.containers).

pom.xml:

<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.javarticles.rest</groupId>
	<artifactId>RESTFulHelloWorld</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>RESTFulHelloWorld</name>

 	<build>
		<finalName>RESTFulHelloWorld</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<inherited>true</inherited>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.glassfish.jersey</groupId>
				<artifactId>jersey-bom</artifactId>
				<version>${jersey.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet-core</artifactId>
			<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
			<!-- artifactId>jersey-container-servlet</artifactId -->
		</dependency>
		<!-- uncomment this to get JSON support <dependency> <groupId>org.glassfish.jersey.media</groupId> 
			<artifactId>jersey-media-moxy</artifactId> </dependency> -->
	</dependencies>
	<properties>
		<jersey.version>2.22.1</jersey.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
</project>

JAX-RS Resource

The main goal of the JAX-RS specification is to make RESTful web service development easier. Jersey provides several annotations which allows one to create the service with ease. All the plumbing work is pushed to the framework so that the developer can focus on the business rule.
In order to mark a POJO class as a service, all you need to is include @Path annotation, specify the path value and you are done. The value of the annotation is the URI relative to the web application context, as deployed in the web server. In our example MyResource.getIt() will act as a RESTFul service. Annotation @GET indicates that the method is handling GET requests. Annotation @Produces indicates that the response will be of text/plain type.

MyResource:

package com.javarticles.rest;

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

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }
}

web.xml

Java EE web application web.xml deployment descriptor under src/main/webapp/WEB-INF. index.jsp is the home page that serves also as a client for MyResource resource.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</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.javarticles.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

Packaging the application into war

In case you want to package the application into a war, run mvn install from the project directory.

C:\javarticles_ws\RESTFulHelloWorld>mvn install
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=64M; support
 was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; sup
port was removed in 8.0
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building RESTFulHelloWorld 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ RESTFulHel
loWorld ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ RESTFulHelloW
orld ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ RE
STFulHelloWorld ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\javarticles_ws\RESTFulHelloWorld\s
rc\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ RESTF
ulHelloWorld ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ RESTFulHelloWorld
---
[INFO]
[INFO] --- maven-war-plugin:2.2:war (default-war) @ RESTFulHelloWorld ---
[INFO] Packaging webapp
[INFO] Assembling webapp [RESTFulHelloWorld] in [C:\javarticles_ws\RESTFulHelloW
orld\target\RESTFulHelloWorld]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\javarticles_ws\RESTFulHelloWorld\src\main\we
bapp]
[INFO] Webapp assembled in [169 msecs]
[INFO] Building war: C:\javarticles_ws\RESTFulHelloWorld\target\RESTFulHelloWorl
d.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ RESTFulHelloWorl
d ---
[INFO] Installing C:\javarticles_ws\RESTFulHelloWorld\target\RESTFulHelloWorld.w
ar to C:\Users\mokkara\.m2\repository\com\javarticles\rest\RESTFulHelloWorld\0.0
.1-SNAPSHOT\RESTFulHelloWorld-0.0.1-SNAPSHOT.war
[INFO] Installing C:\javarticles_ws\RESTFulHelloWorld\pom.xml to C:\Users\mokkar
a\.m2\repository\com\javarticles\rest\RESTFulHelloWorld\0.0.1-SNAPSHOT\RESTFulHe
lloWorld-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.442 s
[INFO] Finished at: 2015-12-09T14:59:23+05:30
[INFO] Final Memory: 12M/309M
[INFO] ------------------------------------------------------------------------

Run the application

Right click on project. Click on ‘Run as’->’Run on server’.

Run RESTFul service from Eclipse

Run RESTFul service from Eclipse

Next select a server. If no server is listed then you need to add a server.
RunRESTFulService_SelectServer

RESTFul webapp home page

RESTFul webapp home page

Call RESTFul Service

Call RESTFul Service

Download the source code

This was an example about RESTFul service using Jersey.

You can download the source code here: RESTFulHelloWorld.zip
Share.

Comments are closed.