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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • kineret

    Hi
    I take this code and run it, but without success.
    The browser open with blank page. and if I look at the “edit component” I see “atatus: 404 not found”.
    I use Intellij, I need to change something in the code?

    Thank you

  • David

    Good introduction to get started, and mess around. It takes a bit of messing around to get it working, but you should have basic j2ee / maven / eclipse experience before starting to use REST

    • kineret

      Hi
      I take this code and run it, but without success.
      The browser open with blank page. and if I look at the “edit component” I see “atatus: 404 not found”.
      I use Intellij, I need to change something in the code?

      Thank you

      • David

        In the context of a local test environment, it is not that easy to work out what exactly is wrong.
        More than likely it is a configuration error.
        Is the rest class on the build path?
        Is it in the correct package? check: com.sun.jersey.config.property.packages param in web.xml
        Have you initiated the request correctly from the browser?

        Might be easier to build the project from a new intellij web project, maybe keep maven out while you try to get it working

  • Yomesh

    Thanks Mkyong. Your blogs are very helpful.

  • samba

    This is very useful site for freshers.

  • sunder

    thanks for a simple example to get me started.

  • Karthik

    Hi Mkyong,

    Tried this example in RAD (with WebSphere App Server), when I try to access the url “*/rest/json/metallic/get”, I get “Error 404: Not Found”, below are the logs when the application is starting,

    Scanning for root resource and provider classes in the packages:
    org.kary.core
    [7/17/13 14:19:07:226 SGT] 00000017 ScanningResou I Root resource classes found:
    class org.kary.core.JSONService
    [7/17/13 14:19:07:230 SGT] 00000017 ScanningResou I No provider classes found.
    [7/17/13 14:19:07:347 SGT] 00000017 WebApplicatio I Initiating Jersey application, version ‘Jersey: 1.8 06/24/2011 12:17 PM’

  • yeshwant

    Hi MKYONG & Other friends of this site:

    I am using JDK 1.5. I have to use this version of JDK. Can you tell me from where to download JDK 1.5 compatible version of JERSEY?

  • Ayan

    Hi MK,
    It was my wife,who heard about ur site from her office-java lecturer and initially (like every husband) I ignored her praise for ur site (u? ;-)

    But for the last 1 month I’m referring your site for setting intrvw qustns as well as giving intervws to top MNCs in d world..

    I must say MK, u rock like MJ (Thriller!)
    ;-)
    Ayan

  • David Balme

    I just wanted to say that I find your website to be very helpful.

    I have come to your site many times for help with various maven issues.

    Thank you for doing this.

    Cheers,
    David

  • Munish kumar

    Hi mkyoung,

    I want to expose restfull services which exist in more than one package. Please suggest the required web.xml configuration for it.

  • Pawan

    Hi, I am not able to figure out how to deploy this app. When I try mvn clean deploy I get the error: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.5:deploy (default-deploy) on project parserclient: Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]

    Will appreciate any hints on how to fix this one.

    Thanks,

    Pawan

  • Corgan

    Hi mkyong,
    I see that your last reply is very old but I want to try ask you something abount Jersey implementation. First of all: thanks for this example.I succeded doing it,it’s work except when large string is passed as parameter.Is it possible to specify in a simple project like this some property like maxReceivedMessageSize? Whitout any specification server return 404 bad request. Can you (or anyone)help me , please?

  • Michael

    Nice one… Thanks for this sample

  • ismail hakki turan
    mvn eclipse:eclipse -Dwtpversion=2.0

    command must be run in project’s path. Users might be type this command like

    mvn archetype:generate -DgroupId=com.mkyong.rest -DartifactId=RESTfulExample -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

    in user path.

    • ismail hakki turan

      and thanks so much for the example.

  • Luis

    It works! Brilliant, as usual…

    Thanks,

    Luis

  • Pingback: Developing REST based Web Services in Java « I, Me & Technology()

  • jd

    Read through the “How to use mkyong tutorial”, I am a newbe. I am getting the error when I run the above application with the url “http://localhost:8080/RESTfulExample/rest/hello/mkyong”, Manifest error. A more verbose content of that error follows; Any heads up appreciated.
    ——–

    PLATFORM VERSION INFO
    	Windows 			: 6.1.7601.65536 (Win32NT)
    	Common Language Runtime 	: 4.0.30319.17929
    	System.Deployment.dll 		: 4.0.30319.17929 built by: FX45RTMREL
    	clr.dll 			: 4.0.30319.17929 built by: FX45RTMREL
    	dfdll.dll 			: 4.0.30319.17929 built by: FX45RTMREL
    	dfshim.dll 			: 4.0.41209.0 (Main.041209-0000)
     
    SOURCES
    	Deployment url			: http://localhost:8080/RESTfulExample/rest/hello/mkyong
     
    ERROR SUMMARY
    	Below is a summary of the errors, details of these errors are listed later in the log.
    	* Activation of http://localhost:8080/RESTfulExample/rest/hello/mkyong resulted in exception. Following failure messages were detected:
    		+ Exception reading manifest from http://localhost:8080/RESTfulExample/rest/hello/mkyong: the manifest may not be valid or the file could not be opened.
    		+ Data at the root level is invalid. Line 1, position 1.
     
    COMPONENT STORE TRANSACTION FAILURE SUMMARY
    	No transaction error was detected.
     
    WARNINGS
    	There were no warnings during this operation.
     
    OPERATION PROGRESS STATUS
    	* [10/12/2012 5:41:03 PM] : Activation of http://localhost:8080/RESTfulExample/rest/hello/mkyong has started.
     
    ERROR DETAILS
    	Following errors were detected during this operation.
    	* [10/12/2012 5:41:03 PM] System.Deployment.Application.InvalidDeploymentException (ManifestParse)
    		- Exception reading manifest from http://localhost:8080/RESTfulExample/rest/hello/mkyong: the manifest may not be valid or the file could not be opened.
    		- Source: System.Deployment
    		- Stack trace:
    			at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
    			at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri&amp; sourceUri, TempFile&amp; tempFile, SubscriptionState&amp; subState, IDownloadNotification notification, DownloadOptions options, ServerInformation&amp; serverInformation)
    			at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri&amp; sourceUri, TempFile&amp; tempFile, SubscriptionState&amp; subState, IDownloadNotification notification, DownloadOptions options)
    			at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String&amp; errorPageUrl)
    			at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
    		--- Inner Exception ---
    		System.Xml.XmlException
    		- Data at the root level is invalid. Line 1, position 1.
    		- Source: System.Xml
    		- Stack trace:
    			at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
    			at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
    			at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
    			at System.Deployment.Application.ManifestValidatingReader.XmlFilteredReader.Read()
    			at System.Xml.XmlCharCheckingReader.Read()
    			at System.Xml.XsdValidatingReader.Read()
    			at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sourceUri)
     
    COMPONENT STORE TRANSACTION DETAILS
    	No transaction information is available.
     
     
    --------
    • LL

      I have exactly same issue. Any suggestion on this?

    • LL

      Solve this issue: by adding @Produces

      package com.mkyong.rest;
       
      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.MediaType;
      import javax.ws.rs.core.Response;
       
      @Path(&quot;/hello&quot;)
      public class HelloWorldService {
       
      	@GET
      	@Path(&quot;/{param}&quot;)
      	@Produces(MediaType.TEXT_PLAIN)
      	public Response getMsg(@PathParam(&quot;param&quot;) String msg) { 
      		String output = &quot;Jersey say : &quot; + msg;
       		return Response.status(200).entity(output).build();
      	}
      }
      • anon

        adding @Produces worked for me too.

  • Joe-Z

    I’m sorry, but this example is absolutely useless.
    I mean, yes you could probably copy all the sources in files and get it wo work. But to me the point of a helloworld-example is getting useres to understand what they are doing and not just what cody to copy in what files (a bit of a ‘teach a man to fish’-thing). From this perspective this introduction really lacks some fundamental explaining of the used components (e.g.: why do i need the ‘web.xml’-file? what do the parameters in ‘pom.xml’ mean? what could be wrong if I’m still getting a 404?)
    I still appreciate that you want to give something back to the community. Only when you do that, do it right.

    • Joe-Z

      code* (not cody)

  • franjo

    Doesn’t work man, 404 error. Any hint?

    • thurman

      I had this problem as well and it was related to how to deploy this app to your tomcat server.

      My problem was fixed by adding a lib folder to the WEB-INF directory.
      Then I copied three jar files into the lib folder:
      asm-3.1
      jersey-core-1.8
      jersey-server-1.8

      I got these jars from my local .m2 folder after I used maven to bring them down for Jersey.
      I’m assuming that you can use google to find them directly, download them, then place them in this folder.
      Remember this ‘lib’ folder is in the {tomcat-home}/webapps/your-app-folder/web-inf folder.

      Another thing that mite seem obvious except for new Tomcat users is that you also have to include a classes folder that contains your class files. This folder is located at
      tomcat-home}/webapps/your-app-folder/web-inf/classes.

      After I added these this demo worked fine.

      One way to really know that you’re on the right track is that after you start Tomcat you should see messages in the console indicating that the Jersey application is being initiated.

      Thurman

    • Vivek

      Worthless example .It didn’t work..If you are reading that tutorial ..it seems good and simple but if you are just implementing this example ..it failed .Worthless .

      I recommand to put the example on the site until it is in running stage .

  • Ramana Reddy

    Hi Mkyong
    I am a great fan of you. Your examples are too good. I use lot of your examples while teaching JSF, Struts, Jax-ws, Jax-rs and all other technologies. You are a great help. Thank you for your service

    ……. Ramana

  • http://springjquery.blogspot.com Priyanka

    Thanks MKYONG………
    Highly appreciate your this effort …
    very useful for beginners like us……

    go ahead…good luck…!!!

  • Vince

    4.0.0
    com.foo.fcm
    server
    war
    1.0-SNAPSHOT
    server Maven Webapp
    http://maven.apache.org

    junit
    junit
    3.8.1
    test

    com.sun.jersey
    jersey-server
    1.8

    maven2-repository.java.net
    Java.net Repository for Maven
    http://download.java.net/maven/2/
    default

    server

    [INFO] ————————————————————————
    [ERROR] BUILD ERROR
    [INFO] ————————————————————————
    [INFO] Error building POM (may not be this project’s POM).

    Project ID: null:jersey-server:bundle:null

    Reason: Cannot find parent: com.sun.jersey:jersey-project for project: null:jersey-server:bundle:null for project null:jersey-server:bundle:null

  • 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

  • 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?

  • 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?

  • 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

      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

  • 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.

    • http://www.mkyong.com mkyong

      Welcome, good to know it help :) keep in touch.

  • http://www.babakaghili.name 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.

  • jaya

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

  • Chandra

    Great Work!!! and Thanks from heart

  • 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

  • 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.

  • 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

  • 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 .

  • Pingback: MAVEN()

  • 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

  • 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.

  • 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.

  • 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.

    • http://www.mkyong.com mkyong

      In this tutorial, Maven is nothing but a build tool, you can get all the dependencies manually and build it manually or via Ant.

  • Pingback: Criando WebServices RESTful com Jersey, Maven e Tomcat no eclipse | Blog do Galluzzo()

  • 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.

    • http://www.mkyong.com mkyong

      your comment is motivated :)

  • Pingback: JAX-RS Tutorial()

  • Kyle

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

    • http://www.mkyong.com mkyong

      Hi, could you explains it in detail? How to simulate it?

      • Corgan

        Hi mkyong,
        I see that last reply is very old but I want to try ask you something abount Jersey implementation. Is it possible to specify in a simple project like this some property like maxReceivedMessageSize? I realized a simple project but with large data passed in input , server return 404 bad request. Can you help me , please?

        • Corgan

          Hi mkyong,
          If param is a string too long I receive a server exception. For example if I read a String from a file and send it with the service and file is too big…