Jersey hello world example

Jersey, reference implementation to develope RESTful web service based on the JAX-RS (JSR 311) specification.

In this tutorial, we show you how to develop a simple hello world REST web application with Jersey.

Technologies and Tools used in this article:

  1. Jersey 1.8
  2. JDK 1.6
  3. Tomcat 6.0
  4. Maven 3.0.3
  5. Eclipse 3.6
Note
If you want to know what and how REST works, just search on Google, ton of available resources.

1. Directory Structure

This is the final web project structure of this tutorial.

folder directory

2. Standard Web Project

Create a standard Maven web project structure.


mvn archetype:generate -DgroupId=com.mkyong.rest -DartifactId=RESTfulExample 
	-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Note
To support Eclipse, use Maven command :


mvn eclipse:eclipse -Dwtpversion=2.0

3. Project Dependencies

Jersey is published in Java.net Maven repository. To develop Jersey REST application , just declares “jersey-server” in Maven pom.xml.

File : pom.xml


<project ...>

	<repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
			<layout>default</layout>
		</repository>
	</repositories>

	<dependencies>
	
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.8</version>
		</dependency>

	</dependencies>
	
</project>

4. REST Service

Simple REST service with Jersey.


package com.mkyong.rest;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
 
@Path("/hello")
public class HelloWorldService {
 
	@GET
	@Path("/{param}")
	public Response getMsg(@PathParam("param") String msg) {
 
		String output = "Jersey say : " + msg;
 
		return Response.status(200).entity(output).build();
 
	}
 
}

5. web.xml

In web.xml, register “com.sun.jersey.spi.container.servlet.ServletContainer“, and puts your Jersey service folder under “init-param“, “com.sun.jersey.config.property.packages“.

File : web.xml


<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>Restful Web Application</display-name>

	<servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		<servlet-class>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
		<init-param>
		     <param-name>com.sun.jersey.config.property.packages</param-name>
		     <param-value>com.mkyong.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>

6. Demo

In this example, web request from “projectURL/rest/hello/” will match to “HelloWorldService“, via @Path("/hello").

And the “{any values}” from “projectURL/rest/hello/{any values}” will match to parameter annotated with @PathParam.

URL : http://localhost:8080/RESTfulExample/rest/hello/mkyong

demo

Download Source Code

References

  1. Jersey Official Website
  2. RESTEasy hello world example
  3. REST with Java (JAX-RS) using Jersey – Tutorial
  4. IBM : RESTful Web services: The basics
  5. RESTful Web Services

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
90 Comment threads
23 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
89 Comment authors
ViktorDimaJohn the Truth TellerDany WehbeLeonidas Recent comment authors
newest oldest most voted
shred lesnar
Guest
shred lesnar

When I am trying to run the same example. I am getting 404 error on server.

Praveen
Guest
Praveen

I am getting this error when I try to run, HTTP Status 500 – Servlet.init() for servlet jersey-serlvet threw exception

The ResourceConfig instance does not contain any root resource classes.

Anyone can help me here to sort out the issue??.

Johaness
Guest
Johaness

as usual an incomplete broken sample!

Nitish
Guest
Nitish

Not true

Nitish
Guest
Nitish
Nitish
Guest
Nitish

If you download his project folder and try to run his, make sure that you spec’s match his, especially the jdk, Jersey and Tomcat version.

CORRECTION:
http://localhost:8080/RESTfulExample/rest/hello/mkyong
(returns a 404 for me)
SHOULD BE
http://localhost:8080/rest/hello/mkyong
(works fine)

This is what got mine to work.
Thanks so much mkyong!

Dorababu
Guest
Dorababu

Hi mkyong I had my XML which was generated using SOAP UI, where I am having some global parameters set. I am trying to execute that XML from maven using continuous integration process I am getting the following error GET – Request_GetAllUsers FailedSubmitException: com.eviware.soapui.model.iface.Request$SubmitException: com.eviware.soapui.impl.wsdl.submit.RequestTransportRegistry$MissingTransportException: Missing protocol in endpoint [${Endpoint}]

Can you help me to over come this

anon
Guest
anon

IF you are using TOmcat 8.5 and Jersey 1.19 then you need to add the below 2 dependecies:

com.sun.jersey
jersey-server
1.19

com.sun.jersey
jersey-servlet
1.19

Juan Marco
Guest
Juan Marco

For those of you having trouble:
1. Make sure you are not mixing jersey 1 with jersey 2.
2. The maven dependency for jersey 1 used in this tutorial INCLUDES
javax.ws.rs, so if you have this dependency below in your pom.xml,
you are in for trouble due to library collisions.

javax.ws.rs
javax.ws.rs-api

The error you get won’t be indicative that this is the problem.

More on stack overflow:
http://stackoverflow.com/questions/23277429/exception-in-rest-jersey

Sathish Kumar
Guest
Sathish Kumar

Hi mkyong,
I am getting the following exception. I am completely blocked can you please help me here.
com.sun.jersey.api.container.ContainerException: No WebApplication provider is present
com.sun.jersey.spi.container.WebApplicationFactory.createWebApplication(WebApplicationFactory.java:69)
com.sun.jersey.spi.container.servlet.ServletContainer.create(ServletContainer.java:412)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.create(ServletContainer.java:327)

Kyle
Guest
Kyle

Just so you know, your site is blocking it’s own images ‘Hotlinking detected’

trackback
JAX-RS Tutorial

[…] JAX-RS implementation.Happy learning JAX-RS Quick StartSome quick start examples to use JAX-RS.Jersey hello world example Jersey framework to create a simple REST style web application.RESTEasy hello world example […]

Rahi Akela
Guest
Rahi Akela

Thanks Mr. Yong,
For your valuable WS-RS tutorials.I had been hunting such a nice WS-RS example since a long time.So thanks a lot.

trackback
Criando WebServices RESTful com Jersey, Maven e Tomcat no eclipse | Blog do Galluzzo

[…] um tutorial bom e de fácil entendimento você encontra no MKYONG . Mas, porém contudo no entanto pule o passo 2, ao invés disso, crie um Dynamic Web Project no […]

M.A.
Guest
M.A.

Hello and thank you for this tutorial. I haven’t started it yet, because I’m not sure if Maven is required and I don’t want to learn it now. So, will I be able to complete this tutorial without using Maven? All I want is to create a web service (rest + json).
Waiting for your reply. Thank you in advance.

C
Guest
C

Took a while to get this to work. I noticed along the way that the latest Jersey release does not work like this, the servlet moved. Another great tutorial though, thank you.

verygood
Guest
verygood

I’m not sure what we could do without you. your tutorials are just perfect. I have never seen anyone on the web who has written such a good and perfect tutorial.
keep up the good work.

Lila Devi
Guest
Lila Devi

Hi,

How can I use ant to build Jax-rs. Is it a simple war file or is there some wsgen tasks that I have to run as with Jax-ws. Please could you provide me with a sample as I do not want to start using Maven just now.

Thanks

trackback
MAVEN
vishwanath
Guest
vishwanath

i have compiled and successfully installed the project but when i try to run it using mvn tomcat:run it doesn’t open any server and just ends .

Henrik
Guest
Henrik

Thank you so much, you made my day!
I could apply this for an endpoint in Mule-ESB (2.28). However I had a small problem, I got a class not found exception for “import com.sun.jersey.spi.service.ComponentProvider”.

However, in the pom, I changed the dependency to the following:

com.sun.jersey.contribs
jersey-simple-server
1.12

and it works nicely. Cheers mate

ranjit
Guest
ranjit

Can you provide us a valuable example for creating a RESTFUL web service using Eclipse and Tomcat. I dont want to use third party tool like jersey that needs license as I dont want to pay annual fees.

Alejandro
Guest
Alejandro

THANK YOU SO MUCH!!! First step-by-step to get this done in less than 5 minutes!!! Thanks… I tried a different site but it seems that the repository was missing. Thanks

Chandra
Guest
Chandra

Great Work!!! and Thanks from heart

jaya
Guest
jaya

Please let me know the procedure to test this.
I’m getting HTTP Status 404 – error

babak
Guest
babak

hello and thanks for your articles.
a question: when I search for Jersey-Server in Maven Central Repo I get the latest version number of 1.3
http://search.maven.org/#search|ga|1|a%3A%22jersey-server%22
but in your example you are using 1.8? I am confused, could you please explain this a little bit.

Thanks.

Pal Ram
Guest
Pal Ram

Hello Mr.Yong,
In recent days, I happen to get perfect answers from your site for most of my Google searches. This is just one of them! So I want to thank you for everything.

Thank you so much for providing such a great help.

Regards,
Ram.

Lin Yang
Guest
Lin Yang

why I run into ‘WARNING: EXCEPTION
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer’ error in eclipse even though I added all jersey and jaxb related jars under GAE war/WEB-INF/lib and Project Properties / Libraries?

marsChen
Guest
marsChen

if you use jersey1.13 version,you should add dependency

com.sun.jersey
jersey-bundle
1.13

in pom.xml?Or add jersey-bundle-1.13.jar in the/WEB-INF/lib

Lin Yang
Guest
Lin Yang

why I run into ‘WARNING: EXCEPTION
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer’ error in eclipse even though I added all jersey ans jaxb related jars under war/WEB-INF/lib and Project Properties / Libraries?

vas
Guest
vas

Thanks…
Does the above example can be deployed on JBoss server and works?
I have created JAXRS webservices using HTTPDispatcherServlet. what is the diff between ServletContainer & HTTPDispatcherServlet? JAX RS webservices servlet entry in web.xml vary based on application server?

s3rcl
Guest
s3rcl

Thanks,
I have gone through couple of Jersey tutorials,
but I have to admit that this is the best one.
Thanks again Mr. Yong