Main Tutorials

RESTEasy hello world example

RESTEasy, JBoss project, implementation of the JAX-RS specification. In this tutorial, we show you how to use RESTEasy framework to create a simple REST style web application.

Technologies and Tools used in this article:

  1. RESTEasy 2.2.1.GA
  2. JDK 1.6
  3. Maven 3.0.3
  4. Eclipse 3.6
What’s REST?
Read this, this and this to understand what’s REST.

1. Directory Structure

Review final directory structure of this tutorial. Just a standard web project structure.

directory structure

2. Standard Web Project

Create a standard Maven web project structure.


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

Convert to Eclipse web project.


mvn eclipse:eclipse -Dwtpversion=2.0

3. Project Dependencies

Declares JBoss public Maven repository and “resteasy-jaxrs” in your Maven pom.xml file. That’s all you need to use RESTEasy.

File : pom.xml


<project ...">

	<repositories>
	   <repository>
		  <id>JBoss repository</id>
		  <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
	   </repository>
	</repositories>

	<dependencies>

		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>2.2.1.GA</version>
		</dependency>

	</dependencies>
</project>

4. REST Service

A simple REST service. See demo at the end of the article, it should be self-explanatory.


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("/message")
public class MessageRestService {

	@GET
	@Path("/{param}")
	public Response printMessage(@PathParam("param") String msg) {

		String result = "Restful example : " + msg;

		return Response.status(200).entity(result).build();

	}

}

5. web.xml

Now, configure listener and servlet to support RESTEasy. Read this JBoss documentation for detail explanation.

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>

	<!-- Auto scan REST service -->
	<context-param>
		<param-name>resteasy.scan</param-name>
		<param-value>true</param-value>
	</context-param>
	
	<!-- this need same with resteasy servlet url-pattern -->
	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/rest</param-value>
	</context-param>

	<listener>
		<listener-class>
			org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
		</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
		</servlet-class>
	</servlet>
     
	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>
Note
You need to set the “resteasy.servlet.mapping.prefix” if your servlet-mapping for the resteasy servlet has a url-pattern other than “/*“.

In above example, the resteasy servlet url-pattern is “/rest/*“, so you have to set the “resteasy.servlet.mapping.prefix” to “/rest” as well, otherwise, you will hit resource not found error message.

Note
Remember to set “resteasy.scan” to true, so that RESTEasy will find and register your REST service automatically.

6. Demo

In this example, web request from “projectURL/rest/message/” will match to “MessageRestService“, and “projectURL/rest/message/{any values}” will match to @PathParam parameter.

Test 1 : http://localhost:8080/RESTfulExample/rest/message/mkyong

example 1

Test 2 : http://localhost:8080/RESTfulExample/rest/message/hello%20world

example 2

Alternative REST Service Registration

In above example, you are register REST service via “ResteasyBootstrap” listener. Here i show you another way.

Create a class and extends javax.ws.rs.core.Application, and add your REST service manually.


package com.mkyong.app;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.mkyong.rest.MessageRestService;

public class MessageApplication extends Application {
	private Set<Object> singletons = new HashSet<Object>();

	public MessageApplication() {
		singletons.add(new MessageRestService());
	}

	@Override
	public Set<Object> getSingletons() {
		return singletons;
	}
}

File : web.xml , no more listener, configure your application class like below :


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

	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/rest</param-value>
	</context-param>

	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
                </servlet-class>
		<init-param>
			<param-name>javax.ws.rs.Application</param-name>
			<param-value>com.mkyong.app.MessageApplication</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>

Done.

Download Source Code

Download it – RESTEasy-Hello-World-Example.zip (7 KB)

References

  1. RESTEasy Framework
  2. RESTEasy installation and configuration
  3. IBM : RESTful Web services: The basics
  4. RESTful Web Services
  5. Wiki : Representational State Transfer

About Author

author image
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

Subscribe
Notify of
59 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Luke
6 years ago

The second link in ‘What’s REST?’ is broken. The correct link is: https://www.ibm.com/developerworks/library/ws-restful/index.html

harikrishnan
7 years ago

how do you given this url?? can you please explain….?
http://localhost:8080/RESTfulExample/rest/message/hello%20world

Shivangi Aneja
7 years ago

Hi..
I am trying to run this example using using Tomcat and Eclipse, but when server gets started Error 404 occurs.
Also when hit correct URL, then also 404 occurs..
No jar error in console…
Please help asap..
Its urgent………

Sandeep K Nair
9 years ago

Hi MKyong,
Thank you for this awesome tutorial.
I have a question. How can we redirect to a page when we hit this service urls (I am trying to develop an application which has services & a monitoring page for the services)
For example lets say my URL is http://localhost:8080/TestApp/rest/monitor
When i hit this URL i wanted the application to navigate to sample-monitor.jsp

I tried the above approach using so, but i was not getting the page that i requested

Service class:

@Path(“/”)

public class TestAppService{

@GET
@Path(“/monitor”)
public void getPage(){

try {
HttpServletRequest req = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
HttpServletResponse res = ResteasyProviderFactory.getContextData(HttpServletResponse.class);

req.getRequestDispatcher(“/sample-monitor.jsp”).forward(req, res);

} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

When i hit the url i get this error

org.jboss.resteasy.spi.NotFoundException: Could not find resource for relative : /sample-monitor.jsp of full path: http://localhost:8080/TestApp/sample-monitor.jsp

but my Application contains the jsp file at the root.

I am using the following jar resteasy-jaxrs-2.2.1.GA.jar in my application.

Sandeep K Nair
9 years ago
Reply to  Sandeep K Nair

Found the issue.

I had the following in my web.xml

resteasy.servlet.mapping.prefix
/

which intercepted all the request as a rest call.

i modified it as below, which makes rest call when url is prefixed with rest/* and ignores other requests (example request for any pages)

resteasy.servlet.mapping.prefix
/rest/*

which fixed my problem.

Hope this will be helpful for someone 🙂

Watchut Awkin
6 years ago

Thanks for this site. I have learnt a lot from here, both from mkyong and the other readers.
I am still new to programming web services and would like to know why mvn generates FOUR projects, namely rest, ejb, rest-web & model..

Please advise which artifacts goes into each of these projects as everywhere I find examples on rest web services, I find everything in a single project and I am sure there has to be some reason for mvn to generate four separate projects…
however, I am too less knowledge to figure it out.. and online searches gives me unrelated answers, as though this has not been asked before..
please help

ThinkingInJava
7 years ago

Thanks for the nice tutorial. Can you please publish a tutorial on the following?

RESTEasy + Spring Security 4.x + OAuth2

It will really be helpful if you can publish it as I did not find any blog/tutorial on this combination on Web.

karl
7 years ago

Thanks mykong, I use your site all the time. You are great.

Ranjit Jadhav
7 years ago

Hi all. I have created rest service but i am facing cross origin problem when i am trying to accessing through ajax call please help me to fix this

Rich
8 years ago

What does it mean when you get a “404 not found” when you run the first demo “http://localhost:8080/RESTfulExample/rest/message/mkyong” ?

Pramod Kumar
7 years ago
Reply to  Rich

It means,,,resource is not available for the particular URL on the server, which u r requesting.

Shivangi Aneja
7 years ago
Reply to  Rich

I am also facing the same issue..
Any idea how to solve it

AB
8 years ago

great post. On TomEE if you make this war it works. If you copy the war and rename it re.war and deploy that as well. Only one of the sites produced works.
Why can’t two sites with restful services work?

vikash
8 years ago

How many ways we can bootstrap my Jax-RS runtime using Resteasy implementation.

markzona
8 years ago

Does not work for me in Wildfly 8.2.0.Final. The only thing I had to do was to add

an “activator” class, to not use a web.xml and no Maven dependencies were needed.

That’s all to get JaxRs running in Wildfly 8.2.0:

@ApplicationPath(“/rest”)
public class JaxRsActivator extends Application
{
}

Zhimeng Jin
8 years ago
Reply to  markzona

For people using JBoss Wildfly 8.2.0.Final & Maven POM, due to the automatic deployment for RestEasy in JBoss Wildfly, the scope of RestEasy dependency in Maven POM needs to be set “Provided” to avoid module conflicts.

org.jboss.resteasy
resteasy-jaxrs
3.0.10.Final
provided

More info., please refer to this question: http://stackoverflow.com/questions/15603662/asynchronousdispatcher-error

Hope it helps!

Gio
9 years ago

Thank you so much. I have spent days trying to properly configure JBoss for Rest Services. I had the same problem with ResteasyBootstrap as Dilip, but alternative method worked well with a little tweaking. I had to manually install some jar libraries, change compiler version in pom, do mvn install on pom.xml, then run on JBoss 7.1. Thanks again.

Claudius Gothicus
9 years ago

Worked well 🙂 On to tinkering with it.

Venkat
9 years ago

Do you have steps for deploying rest service in weblogic 10.3 server. i have below code and need to deploy the same in weblogic server

package com.RS;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
@Path(“/TestHello”)
public class TestJAXRS_Hello {
@GET
@Produces(“text/html”)
public String getString(){
return “TEST JAX-RS”;
}
}

Appreciate your help

Shrestha
10 years ago

I am using Restful web service in eclipse. Few days ago it is running
smoothly. But today, something goes wrong. Web services are running
properly but when I modified something on web service program it does
not reflect after invoking the web service. I have noticed earlier that
whenever I changed small code in my program the server starts
automatically and it reflects on the fly.
Now my web service starts but seems like it runs from cache. Whatever I
modified in the program it does not show in output. I have restart (stop
& start) the server and even restart the eclipse but nothing
changes. It gives always previous results. for example

@Path(“/todo”)
public class TodoResource {
// This method is called if XMLis request
@GET
//@Path(“/text”)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary(“testing web service”);
todo.setDescription(“This is my first todo using restful”);
return todo;
}

when I run this web service, it gives output as

testing web service
This is my first todo using restful

When I modified somthing like (just segement of code 4444 is added)
todo.setSummary(“testing web service 4444”);

it does not display 4444, instead it show older output
testing web service
This is my first todo using restful

Its really strange and I do not know what goes wrong.
Any helps or suggestions are appreciated.

Eclipse Version: Indigo Service Release 2

Thanks in advance

Shrestha

Anadi Kumar
10 years ago

Hey folks,

you need the following jars:

A few of the above jars are not included in the .classpath file.

Regards,

Anadi Kumar
mail – [email protected]

Pavan
10 years ago

Hello mkyong,

This is a nice and simple explanation. I appreciate it.

I have one question regarding the implementation. Is it possible to remove project name in the URL ? (RESTfulExample in your case) to make the URL simple by any means of configuration.

Thanks

Pavan

Smith Wilson
8 years ago
Reply to  Pavan

Yes, rename your project to ROOT, and done.

Sachin
10 years ago

Hey
This is very nice tutorial ,But i need simple token base oAuth in my web service.I had rest easy web services running on tomcat.Can anyone suggest me how can i implement that.

Note – Suppose that oAuth in jboss as7 and web services on tomcat.

Thanks in advance.

http://mototai.ru/
10 years ago

Valuable info. Fortunate me I discovered your site by accident,
and I’m shocked why this coincidence didn’t happened in advance!
I bookmarked it.

comparecarinsurancee11.com
10 years ago

Awesome! Its truly amazing post, I have got
much clear idea regarding from this post.

Ed
10 years ago

Great tutorial, but could use some info on packaging and running.

mvn package

and then to run it and test it quickly from the command line, I added the jetty plugin to the pom

RESTfulExample

org.mortbay.jetty
maven-jetty-plugin

then

mvn jetty:run-war

Thanks!

Ed
10 years ago
Reply to  Ed

looks like the jetty plugin xml did not render…
I’ll try again:

RESTfulExample

org.mortbay.jetty
maven-jetty-plugin

Ed
10 years ago
Reply to  Ed

Still didn’t render. I did use the “to post source code in comment tags, but the xml did not render. Sorry.

Steve
10 years ago

Thanks for this. It worked fine for me.

In case anyone wants to build the war using gradle rather than maven create the following build.gradle file and add this to it:

apply plugin: ‘java’
apply plugin: ‘war’

repositories {
mavenCentral()
}

dependencies {
providedCompile ‘javax.servlet:servlet-api:2.5’
compile ‘javax:javaee-web-api:6.0’
runtime ‘javax.servlet:jstl:1.1.2’
}

Then the command ‘gradle build’ will create the war file in the directory build/libs

Praveen
10 years ago

Is it possible to have multiple prefixes

like /rest /core

Ravi
11 years ago

Hi,

Do you have a tutorial to setup RESTEasy on Tomcat and not on JBoss AS?

Thanks,
Ravi

Ravi
11 years ago
Reply to  Ravi

Well, got it working by simple dropping the war into tomcat’s webapps dir. I thought we had to do something extra for configuring and using resteasy when not using with jboss AS.

mohan
10 years ago
Reply to  Ravi

Hi Ravi,
I have copied the above application in Tomact 6.0 , i have added the jars also.
After deploying while running the application i am getting below error.Please share
what are the extra configurations we need to do at Tomcat End.

Peter
10 years ago
Reply to  mohan

Same; I didn’t know RESTEasy won’t run on Tomcat. I’m wondering how to configure Tomcat…

Mohan
10 years ago
Reply to  Ravi

Hi,
I have deployed the application in Tomcat6.0 , while running the application
i am getting below error
ERROR:”HTTP Status 500 – Wrapper cannot find servlet class org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
or a class it depends on”

please suggest me which plug in i need to add to resolve this.

Leo
11 years ago

Does it work in cross-origin request (CORS)? I couldn’t make it work…

Foster
11 years ago

My partner and I absolutely love your blog and find a lot of your post’s to be exactly I’m looking for. Would you offer guest writers to write content for you? I wouldn’t mind composing a post or elaborating on a few of the subjects you write about here. Again, awesome blog!

Clinton Lobo
11 years ago

Great Tutorial. Your tutorials are always the best. Example code is working & easy to understand. Excellent templates for learning the features of JAX-RS.

Dilip
11 years ago

The above example with Alternative REST Service Registration is working for me but it doesn’t work if I register the service via “ResteasyBootstrap” listener.
I get this error in later case

—————————–
HTTP Status 404 – Could not find resource for relative : /message/mkyong of full path: http://localhost:8089/RESTfulExample/rest/message/mkyong

type Status report

message Could not find resource for relative : /message/mkyong of full path: http://localhost:8089/RESTfulExample/rest/message/mkyong

description The requested resource (Could not find resource for relative : /message/mkyong of full path: http://localhost:8089/RESTfulExample/rest/message/mkyong) is not available.
Apache Tomcat/6.0.29
————————

Jerry
9 years ago
Reply to  Dilip

This issue is explained and resolved here
http://www.javaroots.com/2013/05/creating-rest-services-with-rest-easy.html
You may get error like this : Could not find resource for relative : /application/test of full path: http://localhost:8080/onlinehttpclient/rest/application/test
You have to define resteasy.resource context param with the full path of Rest class.

Aileroiv
10 years ago
Reply to  Dilip

I have the same problem if I try to run the project in IntelliJ. Do you have an idea why not work for me?

Marco
10 years ago
Reply to  Dilip

I have this issue running under RESIN, does anyone fixed the issue?

Thanks,

Crowie
11 years ago
Reply to  Dilip

I’m getting the same error at the moment

DeJu
11 years ago
Reply to  Crowie

I am getting the same error.

Praveen Reddy
11 years ago

Hi,

Will it works on tomcat server.