Professional Documents
Culture Documents
Home
All Tutorials
Java Core
JSF
Spring
Hibernate
Struts
Android
Contact Us
Write For Us
RSS feed
Others
11
5
Like
2
Tw eet
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
Mkyong
Like
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.
Agoda's Best Hotel Offers Save up to 75% Instant confirmation Use your reward points and save! Agoda.com/Hotel_Discounts
REST Test Client Quick, No pain REST service testing Contact us and save 10% wcfstorm.com
$2.95 - Java/JSP Hosting JSP/Java, Servlet Hosting $2.95/mo. Tomcat, Sruts, PHP 5, My SQL 5 www.MochaHost.com
1/14
7/27/13
Note
To support Eclipse, use Maven command :
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
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
2/14
7/27/13
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
References
1.
2.
3.
4.
5.
Tags :
hello world
jax-rs
jersey
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
3/14
7/27/13
mkyong
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him
on Facebook or Google Plus.
Head First
Design
Effective
Spring
JavaScript
Java
Pattern
Java
Recipes
Ninja
Related Posts
Popular Posts
ClassNotFoundException :
com.sun.jersey.spi.container.servlet.ServletContainer
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
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
4/14
7/27/13
yeshwant
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 Im 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
Reply
David Balme
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.
Reply
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
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
5/14
7/27/13
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,its 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?
Reply
Michael
Nice one Thanks for this sample
Reply
command must be run in projects path. Users might be type this command like
in user path.
Reply
Reply
Luis
It works! Brilliant, as usual
Thanks,
Luis
Reply
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.
: 6.1.7601.65536 (Win32NT)
: 4.0.30319.17929
: 4.0.30319.17929 built by: FX45RTMREL
: 4.0.30319.17929 built by: FX45RTMREL
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
6/14
7/27/13
Deployment url
: http://localhost:8080/RESTfulExample/rest/hello/mkyong
SOURCES
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 dete
+ Exception reading manifest from http://localhost:8080/RESTfulExample/rest/hello/mkyong: the manifest may not be valid or
+ 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
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ManifestReader.FromDocument(String localPath, ManifestType manifestType, Uri sour
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore
at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri&
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isSho
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 sour
COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.
--------
Reply
LL
LL
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("/hello")
public class HelloWorldService {
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
7/14
7/27/13
Reply
anon
Joe-Z
Im 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 helloworldexample 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 Im 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.
Reply
Joe-Z
franjo
Doesnt work man, 404 error. Any hint?
Reply
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.
Im 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.
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
8/14
7/27/13
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
Reply
Priyanka
Thanks MKYONG
Highly appreciate your this effort
very useful for beginners like us
go aheadgood luck!!!
Reply
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 projects 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
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
9/14
7/27/13
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
Reply
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?
Reply
Lin Yang
Lin Yang
marsChen
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.
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
10/14
7/27/13
mkyong
babak
jaya
Chandra
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
Reply
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.
Reply
Henrik
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
11/14
7/27/13
vishwanath
i have compiled and successfully installed the project but when i try to run it using mvn tomcat:run it doesnt open any
server and just ends .
Reply
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
Reply
verygood
Im 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.
Reply
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.
Reply
M.A.
Hello and thank you for this tutorial. I havent started it yet, because Im not sure if Maven is required and I dont 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.
Reply
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.
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
12/14
7/27/13
Rahi Akela
mkyong
your comment is motivated :)
Reply
Kyle
Just so you know, your site is blocking its own images Hotlinking detected
Reply
mkyong
Hi, could you explains it in detail? How to simulate it?
Reply
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?
Reply
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
Reply
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
13/14
7/27/13
Note
To post source code in comment, uses <pre lang="java"> source code </pre>
Post Comment
Notify me of followup comments via e-mail
Recruitment Canada
www.wcfstorm.com
www.MochaHost.com
WCF Functional & Load Testing tool JSP/Java, Servlet Hosting $2.95/mo.
Also works with Web Services!
Tomcat, Sruts, PHP 5, My SQL 5
jobrapido.com/recruitment+can
www.Qwords.com
5 urgent open positions. Apply now! Redundant Cloud Storage Mulai
Recruitment Canada
Rp.300 / hari
Favorites Links
About Us
Android Developer
PHP Tutorials
Java Misc
TenthOfMarch
J2EE Frameworks :
Web Development
We're Social
1. Twitter - Follow Me
2. Facebook - Like Me
3. Google Plus - Add Me
4. RSS - Subscribe Me
Copyright 2008-2013 Mkyong.com, all rights reserved. Web Hosting Powered by Liquid Web
www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
14/14