Spring RESTful Web Service Tutorial

Modularize Spring application
December 9, 2012
Force maven to download dependencies in Eclipse
December 10, 2012

Creating RESTful web service is very simple with Spring web module. In this tutorial, I will show how to create a web service which performs CRUD operations on a bean using the HTTP methods.

The bean class:

There is nothing special about this bean class except the XmlRootElement annotation which is part of JDK. This annotation is used to tell the root element under which the member variables shall be enclosed in an XML representation of an object of this class. As XML root element is specified as Employee in this class, a valid XML representation of an object of Employee class shall be:

<?xml version="1.0" encoding="UTF-8"?>

Note that the name of child elements is same as the names of member variables.

package com.javaexperience.employee;

import javax.xml.bind.annotation.XmlRootElement;

public class Employee {

	private int empId;
	private String deptName;

	public int getEmpId() {
		return empId;
	public void setEmpId(int empId) {
		this.empId = empId;
	public String getDeptName() {
		return deptName;
	public void setDeptName(String deptName) {
		this.deptName = deptName;

The controller which perform CRUD operations:

The controller here performs four operations viz. create, read, update and delete. The operations are performed on a member ArrayList of type Employee. In real world. you should be using some data source to store the bean objects. The important annotations to notice here are:

  • @Controller
  • @RequestMapping
  • @ResponseBody
  • @PathVariable
  • @RequestBody

Since JDK comes with support for JAXB, the objects are automatically marshaled and un-marshaled as and when required. Some points to note about the controller are:

1) The RequestMapping annotation completes the URL for invoking each REST operation. For example for get operation in our case, the final URL shall be http://localhost:8080/SpringRSWebService/services/getEmp/1 or http://localhost:8080/SpringRSWebService/services/getEmp/2. The number at the end signifies employee id. This number is then passed as argument to the getEmployee method by using the @PathVariable annotation.
2) The @ResponseBody annotation tell Spring that client should be sent whatever the method sends as return value.
3) For read and delete operations, HTTP GET and DELETE methods should be used. There is some debate on which method to be used for create and update. Here I have used POST for create and PUT for update operations.

package com.javaexperience.main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaexperience.employee.Employee;

public class EmpController
	List<Employee> list = new ArrayList<Employee>();

	@RequestMapping(value = "/getEmp/{emp}", method = RequestMethod.GET)
	public @ResponseBody Employee getEmployee(@PathVariable("emp") int empid) {
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee emp = (Employee) iterator.next();
			if(emp.getEmpId()==empid) {
				return emp;
		return new Employee();

	@RequestMapping(value = "/removeEmp/{emp}", method = RequestMethod.DELETE)
	public @ResponseBody String removeEmployee(@PathVariable("emp") int empid) {
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee emp = (Employee) iterator.next();
			if(emp.getEmpId()==empid) {
				return "Employee Successfully removed";
		return "Employee Not found";

    @RequestMapping(value = "/addEmp",
			method = RequestMethod.POST)
	public @ResponseBody String addEmployee(@RequestBody Employee emp) {
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee tempEmp = (Employee) iterator.next();
			if(tempEmp.getEmpId()==emp.getEmpId()) {
				return "Employee already present. No need to add again";
				return "Employee Successfully Added";

    @RequestMapping(value = "/updateEmp",
			method = RequestMethod.PUT)
	public @ResponseBody String updateEmployee(@RequestBody Employee emp) {
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee tempEmp = (Employee) iterator.next();
			if(tempEmp.getEmpId()==emp.getEmpId()) {
				return "Employee Successfully updated";
		return "Employee Not found";

The web deployment descriptor:

The deployment descriptor for out RESTful web service is same as that of any Spring Web MVC project. The DispatcherServlet and ContextLoaderListener have been configured in standard way. The only thing you can consider of changing is the URL of web service operations. For example, the DispatcherServlet is mapped to /services/* so the URL for our web service shall be : http://localhost:8080/[context]/services/[operation]

<?xml version="1.0" encoding="UTF-8"?>
<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">





The Spring application context xml file:

The application context tell the Spring framework the location of folder where it can find the controller and initialize them. In our case the controller named EmpController is present in com.javaexperience.main package. This controller as explained above implements the web service CRUD operations.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

	<!-- Activates various annotations to be detected in bean classes -->
	<context:annotation-config />

	<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
	 For example @Controller and @Service. Make sure to set the correct base-package-->
	<context:component-scan base-package="com.javaexperience" />

	<!-- Configures the annotation-driven Spring MVC Controller programming model.
	Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
	<mvc:annotation-driven />


The spring servlet xml file:

Since we haven’t added any view jsp or html, the spring-servlet.xml file is blank. Note that the file has to be named as spring-servlet.xml because we configured the DispatcherServlet with name “spring” in web.xml. If you decide to return a view from controller, then you should be adding view resolver mapping in this xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

Publishing the web service

In order to publish the above REST web service, we need a java web container like Tomcat or JBoss. Simply download the application zip from the link at the end of this tutorial and unzip it to webapps folder of tomcat. The downloadable zip has all the dependencies available in it. If you want to configure the project in Eclipse, then either you can add it as a normal Java project else import it as a Spring maven project and run maven install.

If you get any error while publishing the web service sample, leave a comment with error log.

Consuming Spring RESTful web service:

First let me list the URL’s for accessing the REST web service which we just created:

Create Employee (HTTP POST method):


The body of request should contain valid xml to represent Employee bean class. For example:

<?xml version="1.0" encoding="UTF-8"?>

When creating the employee, make sure to send the HTTP Content-type header as “application/xml”. By doing so, you are telling the server that the request contains xml data which shall then be marshaled into an instance of Employee bean class and injected into addEmployee method of our Spring REST web service application.

Get Employee (HTTP GET method):


Delete Employee (HTTP DELETE method):


This method is very similar to get method as the employee to be deleted is specified by appending corresponding employee id at the end of URL

Update Employee (HTTP PUT method):


The body of PUT request shall contain an XML representation of Employee object. As mentioned earlier too, the PUT request is very similar to POST request. Here also we need to send an HTTP header of Content-type with value as application/xml.

For sending the GET request, you can simply put the GET url in the web browser address bar. But for sending other type of requests, you need to use a HTTP client like REST Client add-on for FirefoxJava based REST client application.

If you get stuck with consumption of this Spring web service then do leave a comment regarding the same.

I have uploaded this sample application on cloud. Use the following URL’s to access the web service:

http://springrswebservice.extremejava.cloudbees.net/services/addEmp (use RESTClient for adding body)
http://springrswebservice.extremejava.cloudbees.net/services/updateEmp/1 (use RESTClient for adding body)

The complete code for this application in zip format can be downloaded from link given below: