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

Download it – JAX-RS-Hello-World-Jersey-Example.zip (6 KB)

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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
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??.

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!

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)

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

Sure Law
Guest
Sure Law

To run the demo, do as following steps: 1. Get a servlet container. I use eclipse jetty to do this, and of course tomcat is fine too. 2. cd into base dir of this example and run “mvn clean install”. If you are luck enough, you will get a file named as “RESTfulExample.war” in the target folder. 3. move this file into jetty_home/webapps, and start jetty using command ” java -jar start.jar”. 4 Now, you can access the url refered in author’s blog.

Karthick A S
Guest
Karthick A S

hi Mkyong, I am trying above sample in my weblogic server….i am facing some issue. Is there i need to add any new jars related to weblogic server.

Und
Guest
Und

Not work

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

neeraj bansal
Guest
neeraj bansal

works for me, thanks

Sydney
Guest
Sydney

And I forgot to configure my server :( Done it now and the example is working perfectly :) … Big-ups to Mkyong

Sydney
Guest
Sydney

Hi, MK, Thanks for delivering such great work. I have been benefiting from your tutorials for a while now. I am currently trying to get this one to work and be able to understand thoroughly. If I may ask, where do we configure the port number? ‘8080’ in your example?

Rishi Prakash
Guest
Rishi Prakash

By default your server will be configured with 8080 port.

Michael Njoroge
Guest
Michael Njoroge

its a cool one..

Arno Jan Sta Nimus
Guest
Arno Jan Sta Nimus

Why are you all using this com.sun packages?? they are likely to be removed from api!!

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

Capricorn1
Guest
Capricorn1

This was all I needed to get started in the right direction. Thanks!

RAYO
Guest
RAYO

This example to uses qith JBoss 6 I need to change the web.xml

jersey-serlvet
com.sun.jersey.spi.container.servlet.ServletContainer

com.sun.jersey.config.property.packages
mx.com.sia.tutorial.rest

1

jersey-serlvet
/*

resteasy.scan
false

resteasy.scan.providers
false

resteasy.scan.resources
false

Saludos!!!!

Nagarjuna
Guest
Nagarjuna

Hi Sir, This is nagarjuna working for MNC, i have copied this project into my eclipse and converted into maven .
it is not working, am referring to different url. can you provide settings .xml for this project

Eduardo Oportus
Guest
Eduardo Oportus

very helpfull, thank you.

Johaness
Guest
Johaness

fucker!!!!

Johaness
Guest
Johaness

No provider classes found.

Johaness
Guest
Johaness

GRAVE: Servlet [jersey-serlvet] in web application [/restSample] threw load() exception

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)

at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)

at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:506)

at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:488)

at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:115)

at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148)

at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)

at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5266)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5554)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)

at java.util.concurrent.FutureTask.run(FutureTask.java:266)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

at java.lang.Thread.run(Thread.java:745)

Johaness
Guest
Johaness

as usual an incomplete broken sample!

Nitish
Guest
Nitish

Not true

Murali Mohan
Guest
Murali Mohan

Hi, i am getting the below deployment exception when i deployed in websphere 8.0, but it works well in tomcat server. Could you please let me know what was the issue?
java.lang.NoSuchMethodError: javax/ws/rs/core/Application.getProperties()Ljava/util/Map;

at org.glassfish.jersey.server.ApplicationHandler.(

java.lang.NoSuchMethodError: javax/ws/rs/core/Application.getProperties()Ljava/util/Map;

at org.glassfish.jersey.server.ApplicationHandler.(

ApplicationHandler.java:287)

RAJ
Guest
RAJ

Hi everyone,

i just created this example in my machine, and when i tried to access it via the example URL mentioned below, i am getting Bad request 400 error in all the browsers.

http://localhost:8080/RESTfulExample/rest/hello/Raj

Did anyone faced this issue? If so, any help would be great.

Find below the request from browser:

Remote Address: [::1]:8080
Request URL: http://localhost:8080/RESTfulExample/rest/hello/Rajkumar
Request Method: GET
Status Code: 400 Bad Request

Thanks in advance…

Guest
Guest
Guest

Is it jersey-servlet or jersey-servlvet

hbeira
Guest
hbeira

Thanks!

Jayani
Guest
Jayani

Thank you! :) This works.

Rahul Gonnade
Guest
Rahul Gonnade

this service runs perfectly on local server(localhost:8080).. but hen deployed on actual webserver(xyz.com) shows error

The requested URL “rest/hello/mkyong” was not found on this server.

Please help me out

Followed up the deployment process but still getting same error