Spring 3 REST Example

In this article, you will how to create a RESTful web service using the Spring framework.

Spring’s annotation-based MVC framework serves as the basis for creating RESTful Web Services.

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

    <!-- Spring 3 dependencies -->

1. Controller

In Spring 3, the use of URI templates is introduced through the @PathVariable annotation. Spring uses the @RequestMapping method annotation to define the URI Template for the request.


package com.kruders.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;

public class PersonController {
	@RequestMapping(value = "/{fname}/{lname}", method = RequestMethod.GET)
	public String getMovie(@PathVariable String fname, @PathVariable String lname, ModelMap model) {
		model.addAttribute("firstname", fname);
		model.addAttribute("lastname", lname);
		return "person";

When a request comes in for /person/Puneet, that Puneet will be bound to the fname parameter.

2. Create View

Create jsp folder in WEB-INF and create person.jsp file in jsp folder

Now write the following code in person.jsp file

	<b>Spring MVC REST Example</b>
	First Name : ${firstname}
	Last Name : ${lastname}

3. Configuration

Create Spring Bean Configuration in WEB-INF folder and name it dispatcher-servlet.xml and add the following code.

<context:component-scan base-package="com.kruders.controller" />
    <property name="prefix">
    <property name="suffix">

4. Integrate Spring in Web App

To integrate Spring in Web Application, write the following code in web.xml


5. Run

Now when you run the project, following screen will be displayed as in Figure 67.1

Figure 67.1 Figure 67.1

The folder structure of the example is shown below in Figure 67.2

Figure 67.2 Figure 67.2

You can download the source code of this example here.

, ,

No comments yet.

Leave a Reply