RESTFul Web Service Example with Jersey 2 and Tomcat 8

Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.

Let’s make an RESTFul web service example with Jersey 2 and Tomcat 8. Our web service is taking a word as parameter, reverse it and return that reversed word as response.

This is how Package Explorer is going to look like:

jersey1

Follow File > New > Dynamic Web Project to create project in Eclipse.

Do not forget to check box “Generate web.xml deployment descriptor” in last page of setup wizard because we need web.xml file.

jersey2

jersey3

Right click project > Configure > Convert to Maven Project.

Right click project > Properties > Java Build Path add

javax.ws.rs-api-2.0.1 (comes with Jersey, find in jersey/api folder)

json-20151123 (can be downloaded from here)

We also going to add dependencies in pom.xml for these two.

In web.xml we define a rule about URLs which match with “/reverser/*” pattern is routed to “com.rest.jersey2” package.

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>RestWithJersey2</groupId>
	<artifactId>RestWithJersey2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>2.22.1</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20151123</version>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xmlns="http://xmlns.jcp.org/xml/ns/javaee" 	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 	id="WebApp_ID" version="3.1">
	<display-name>RestWithJersey2</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>Rest With Jersey2</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.rest.jersey2</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Rest With Jersey2</servlet-name>
		<url-pattern>/reverser/*</url-pattern>
	</servlet-mapping>
</web-app>
package com.rest.jersey2;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.json.JSONException;
import org.json.JSONObject;

@Path("/jsonbasedreverser")
public class JSONBasedReverser {

	@GET
	@Produces("application/json")
	public Response defaultReverser() throws JSONException {

		StringBuilder sb = new StringBuilder();
		sb.append("ANKARA");

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("original", sb.toString());
		jsonObject.put("reversed", sb.reverse().toString());

		String result = "" + jsonObject;
		return Response.status(200).entity(result).build();
	}

	@Path("{word}")
	@GET
	@Produces("application/json")
	public Response reverser(@PathParam("word") String word) throws JSONException {

		StringBuilder sb = new StringBuilder();
		sb.append(word);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("original", sb.toString());
		jsonObject.put("reversed", sb.reverse().toString());

		String result = "" + jsonObject;
		return Response.status(200).entity(result).build();
	}

}

package com.rest.jersey2;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/xmlbasedreverser")
public class XMLBasedReverser {
	@GET
	@Produces("application/xml")
	public String defaultReverser() {

		StringBuilder sb = new StringBuilder();
		sb.append("ANKARA");

		return "<word>" + "<original>" + sb.toString() + "</original>" + "<reversed>" + sb.reverse().toString()
				+ "</reversed>" + "</word>";
	}

	@Path("{word}")
	@GET
	@Produces("application/xml")
	public String reverser(@PathParam("word") String word) {
		StringBuilder sb = new StringBuilder();
		sb.append(word);

		return "<word>" + "<original>" + sb.toString() + "</original>" + "<reversed>" + sb.reverse().toString()
				+ "</reversed>" + "</word>";
	}

}

Ready to build and deploy.

Go to:

http://localhost:8080/RestWithJersey2-0.0.1-SNAPSHOT/reverser/jsonbasedreverser

http://localhost:8080/RestWithJersey2-0.0.1-SNAPSHOT/reverser/jsonbasedreverser/istanbul

http://localhost:8080/RestWithJersey2-0.0.1-SNAPSHOT/reverser/xmlbasedreverser

http://localhost:8080/RestWithJersey2-0.0.1-SNAPSHOT/reverser/xmlbasedreverser/istanbul

jersey4

jersey5

Resources:

[1] http://crunchify.com/how-to-build-restful-service-with-java-using-jax-rs-and-jersey/

[2] https://wolfpaulus.com/journal/java-journal/jersey/

[3] http://tutorial-academy.com/restful-webservice-jersey-maven/

[4] http://stackoverflow.com/questions/18086218/java-lang-classnotfoundexception-com-sun-jersey-spi-container-servlet-servletco

Advertisements

4 thoughts on “RESTFul Web Service Example with Jersey 2 and Tomcat 8

  1. Stefan Schmors says:

    Right click project > Properties > Java Build Path add is where You lost me… unfortunately when I open this dialog I get about 10 different options and as I am trying to learn (this is why I am here) I would have expected more details:
    — why do I have to add the javax.ws.rs-api-2.0.1 to the build path, in which way and what am I trying to achieve anyway…

    I went from here to Thorsten Horns page on how to set up a jax something, and on his 87 pages I find things covered in more detail.

    Thanks anyway!

  2. sanjiv says:

    Good article. Thank you.
    Just so it helps someone else …. you would have to add the following to your eclipse build path:
    jax-ws-rs, jersey-container-servlet, json jars.
    Post this add the above build path jars in deployment assembly.
    Please also note that in web.xml, this entry by the author: com.rest.jersey2 actually stands for his example application. Change it to yours (my eyes missed it) ….
    Regards,

  3. Jai Berman says:

    Thanks for the article. Anyway the title expect me to run it on a Tomcat Server instead of Glassfish. How do I run it in tomcat ? What dependencies I have to add.

  4. AndyFaizan says:

    Your article helped me a lot. Thanks a ton!

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

%d bloggers like this: