Main Tutorials

Spring 3 REST hello world example

In Spring 3, old RequestMapping class is enhanced to support RESTful features, which makes Spring developers easier to develop REST services in Spring MVC.

In this tutorial, we show you how to use Spring 3 MVC annotations to develop a RESTful style web application.

1. Project Directory

Review the project folder structure.

2. Project Dependency

To develop REST in Spring MVC, just include the core Spring and Spring MVC dependencies.

pom.xml

	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

	</dependencies>

</project>

3. REST Controller

For Spring RESTful, you need PathVariable, RequestMapping and RequestMethod. Following code should be self-explanatory.

MovieController.java

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/movie")
public class MovieController {

	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String getMovie(@PathVariable String name, ModelMap model) {

		model.addAttribute("movie", name);
		return "list";

	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String getDefaultMovie(ModelMap model) {

		model.addAttribute("movie", "this is default movie");
		return "list";

	}

}

4. JSP Views

A JSP page to display the value.

list.jsp

<html>
<body>
	<h1>Spring 3 MVC REST web service</h1>
	
	<h2>Movie Name : ${movie}</h2>	
</body>
</html>

5. Demo

See REST URLs demonstration.

URL : http://localhost:8080/SpringMVC/movie/ironMan

Spring MVC REST demo

URL : http://localhost:8080/SpringMVC/movie/SpiderMan4

spring mvc rest demo

Download Source Code

References

  1. http://en.wikipedia.org/wiki/Representational_State_Transfer
  2. http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

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
61 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Puja Bhatt
7 years ago

This tutorial is very helpful. I learn alot from this. Thanks to author

Nirajan
8 years ago

I don’t think it is a REST. The response of a RESTful web service is either in JSON or XML. The response should not be in jsp like you presented. And specially, this is just an Spring MVC Hello World.

Deepak ss
7 years ago
Reply to  Nirajan

you r correct 🙂

Ahmed Harchaoui
7 years ago
Reply to  Nirajan

i agree with you !

Thirumala Nagaraju
4 years ago

I just imported this as java project and when i execute the given url in this page after deploying the project in server its showing 404 error. i really don’t understand the reason for this. please check every thing once before u give download option to someone

NSLabs
7 years ago

Mr.Nirajan is right

NSLabs
7 years ago

Yes, Worked Fine

Pavani
8 years ago

I have imported the same downloaded project into eclipse,while running,it is showing the error as “java Exception has occurred”classnotfoundException
someone help me plz,I am new to this concept.

zak
8 years ago

This is how to generate documentation using Swagger, after creating the Rest API:
http://opentechcode.blogspot.com/2015/09/generating-rest-services-documentation.html

ishan bakshi
8 years ago

Just been looking at the hello world tutorial as well at : https://mkyong.com/spring3/spring-3-mvc-hello-world-example/

I could not find any difference other than in this tutorial a value called {name} is being passed. Can anyone tell me… is the normal hello world program also a REST request?

kiki
9 years ago

How to compile this project?

Victor
9 years ago
Reply to  kiki

SpringMVC:> mvn clean install

Ajit Kumar
9 years ago

Hello sir;

I am new to Spring with REST call.

so try to learn this from your above example but am facing Requested HTTP URI not found issue,

means when am trying provide a external resource link for My CSS and JQuery file it not able to load these files to my jsp. but if change the :from

dispatch
/

—-To—–

dispatch
*.html

then my CSS and JQuery files are working but rest Call is not working

please any one help me out………………………

akshay jain
9 years ago

By downloading and importing project into eclipse it works fine. But how to create the project with same directory structure ? We created new-> dynamic web project. But it has different directory structure.

hilda
9 years ago

Need Help! I did everything mentioned here and the url says noHandler found! Any thoughts.

razesh
9 years ago

you are awesome, your examples are startup for me thanks again

Rahman
10 years ago

i did everything ..it worked for the first time but it stopped working …so sometimes even you follow the instructions but you should clean the tomcat or whatever server used. After which, it worked fine…thanks

Oswaldo
10 years ago

It works as expected, but I`m figuring out that the spring context is loaded several times, you can see on output log.

INFO: Initializing Spring root WebApplicationContext
Sep 18, 2013 12:59:39 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started

INFO: Root WebApplicationContext: initialization completed in 850 ms
Sep 18, 2013 12:59:40 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet ‘mvc-dispatcher’
Sep 18, 2013 12:59:40 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet ‘mvc-dispatcher’: initialization started

INFO: FrameworkServlet ‘mvc-dispatcher’: initialization completed in 158 ms
Sep 18, 2013 12:59:40 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/oswaldo/opt/Tomcat/webapps/Spring-MVC
Sep 18, 2013 12:59:40 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext

INFO: Root WebApplicationContext: initialization completed in 637 ms
Sep 18, 2013 12:59:41 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet ‘mvc-dispatcher’
Sep 18, 2013 12:59:41 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet ‘mvc-dispatcher’: initialization started

INFO: FrameworkServlet ‘mvc-dispatcher’: initialization completed in 152 ms
Sep 18, 2013 12:59:41 PM org.apache.coyote.AbstractProtocol start

I think there is something wrong here

Jay Vee
10 years ago

The downloaded .zip does not work. There needs to be a modification in the mvc-dispatcher-servlet.xml to make this work. the property name=”prefix” should have the value /WEB-INF/ removed or it will not work.

It should look like this:

/jsp/

.jsp

It Jobs
10 years ago

Thank you and it is excellent Tech Article .. It useful for Spring learner

Saraby
10 years ago

It works perfectly. Thanks!!!

shams
10 years ago

Thanks for a wonderful post.
This post will be helpful if any one interested to see how the spring framework supports JSON output from the restful web service
http://www.smashplus.info/2013/05/restful-web-service-in-spring-framework.html

Paul
10 years ago

Quick and dirty but doesn’t really explain much. As with SpringMVC tutorial some setup instructions would be nice. You might have named the project SpringMVCRest to differentiate it from the SpringMVC project tutorial and avoid namespace conflicts.

Charan D
10 years ago

Can you upload spring + Hibernate+ RestFull implementation please.

sean
10 years ago

Thanks for the great example!

If I may, I have one observation regarding getDefaultMovie’s @RequestMapping; use an empty string instead of a single forward slash.

 
@RequestMapping(value = "", method = RequestMethod.GET)
	public String getDefaultMovie(ModelMap model) {

The reason is while “localhost:8080/SpringMVC/movie/” displays the default movie message “localhost:8080/SpringMVC/movie” returns 404.

When an empty string is used, both return default movie message.

There are a lot of comments, sorry if this was previously stated.

Jeff
10 years ago
Reply to  sean

Nice Observation! It worked.. Thanks Sean!

@mykong… thanks for the tutorial, its simple and perfect, worked like a charm. Great work!

jakki
11 years ago

java.lang.illegalstateexception no parameter name specified for argument of type java.lang.string i got this exception

When i changed the code from this

@RequestMapping(value = “/{name}”, method = RequestMethod.GET)
public String getMovie(@PathVariable String name, ModelMap model) {

to this its working now have to add (@PathVariable(“name”))

jakki
11 years ago

java.lang.illegalstateexception no parameter name specified for argument of type java.lang.string i got this exception

When i changed the code from this

@RequestMapping(value = “/{name}”, method = RequestMethod.GET)
public String getMovie(@PathVariable String name, ModelMap model) {

to this its working now have to add (@PathVariable(“name”))

@RequestMapping(value = “/{name}”, method = RequestMethod.GET)
public String getMovie(@PathVariable(“name”) String name, ModelMap model) {

Anand
11 years ago

I have a doubt. The example looks like normal web application but still serves as RESTful service. Here I see there is no reference implementation for JAX-RS is used. So, can I assume that JAX-RS standards are not required or irrelevant with Spring 3.0?

Amar
11 years ago

Nice articles…Y dont you make it available on github only…

Nitin Gupta
11 years ago

I am newbie to Java and Spring, and i love Mkyong for for his wonderful tutorials and examples. It helps me a lot.

Preetam
11 years ago

how can i use cxf with spring mvc can u provide a full article on that ?

jonathan
11 years ago

Nice little guide but you forgot to show and describle one of the most important parts of setting up a Restful web application and that is the mvc dispatcher and web.xml files.

Without this, the application wont work and the people here using this example as a starting point will strugle to play around and develope this app further.

Please update your post and include details about the web.xml file and teh dispatcher!

this is vital as a user can then tweak and add more controllers, more mappings and change the mapping patterns completely

shari222
10 years ago
Reply to  jonathan

Thank u so much. as i wasted so much time, trying running this proj.