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"?>
<Employee>
    <empId>10</empId>
    <deptName>abc</deptName>
</Employee>

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;

@XmlRootElement(name="Employee")
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;

@Controller
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) {
				iterator.remove();
				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";
			}
		}
				list.add(emp);
				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()) {
				tempEmp.setDeptName(emp.getDeptName());
				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">
	
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
</web-app>

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"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd


http://www.springframework.org/schema/mvc


http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

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

</beans>

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"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

</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):

http://localhost:8080/SpringRSWebService/services/addEmp/

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

<?xml version="1.0" encoding="UTF-8"?>
<Employee>
    <empId>1</empId>
       <deptName>abc</deptName>
</Employee>

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

http://localhost:8080/SpringRSWebService/services/getEmp/1/

http://localhost:8080/SpringRSWebService/services/getEmp/2/

http://localhost:8080/SpringRSWebService/services/getEmp/3/

…………………
…………………

Delete Employee (HTTP DELETE method):

http://localhost:8080/SpringRSWebService/services/removeEmp/1/

http://localhost:8080/SpringRSWebService/services/removeEmp/2/

http://localhost:8080/SpringRSWebService/services/removeEmp/3/

………………..
………………..

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

http://localhost:8080/SpringRSWebService/services/updateEmp/

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/getEmp/1

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

http://springrswebservice.extremejava.cloudbees.net/services/removeEmp/1

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:

Related Posts

Spring RESTful Web Service Tutorial admin Spring
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...
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. <a target="_blank" rel="nofollow" href="http://springrswebservice.extremejava.cloudbees.net/services/getEmp/1"><img src="http://www.javaexperience.com/wp-content/uploads/2012/12/demo.jpg"/></a> <h2>The bean class:</h2> 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: 1 Note that the name of child elements is same as the names of member variables. 1 <h2>The controller which perform CRUD operations:</h2> 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: <ul> <li>@Controller</li> <li>@RequestMapping</li> <li>@ResponseBody</li> <li>@PathVariable</li> <li>@RequestBody</li> </ul> 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. 1 <h2>The web deployment descriptor:</h2> 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] 1 <h2>The Spring application context xml file:</h2> 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. 1 <h2>The spring servlet xml file:</h2> 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. 1 <h2>Publishing the web service</h2> In order to publish the above REST web service, we need a java web container like <a href="http://www.javaexperience.com/category/tomcat/">Tomcat</a> 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 <a href="http://www.javaexperience.com/spring-maven-project-using-eclipse-plugin/">Spring maven project</a> and run maven install. If you get any error while publishing the web service sample, leave a comment with error log. <h2>Consuming Spring RESTful web service:</h2> <a target="_blank" rel="nofollow" href="http://springrswebservice.extremejava.cloudbees.net/services/getEmp/1"><img src="http://www.javaexperience.com/wp-content/uploads/2012/12/demo.jpg"/></a> First let me list the URL's for accessing the REST web service which we just created: <h3>Create Employee (HTTP POST method): </h3> http://localhost:8080/SpringRSWebService/services/addEmp/ The body of request should contain valid xml to represent Employee bean class. For example: 1 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. <h3>Get Employee (HTTP GET method):</h3> http://localhost:8080/SpringRSWebService/services/getEmp/1/ http://localhost:8080/SpringRSWebService/services/getEmp/2/ http://localhost:8080/SpringRSWebService/services/getEmp/3/ ..................... ..................... <h3>Delete Employee (HTTP DELETE method):</h3> http://localhost:8080/SpringRSWebService/services/removeEmp/1/ http://localhost:8080/SpringRSWebService/services/removeEmp/2/ http://localhost:8080/SpringRSWebService/services/removeEmp/3/ .................... .................... 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 <h3>Update Employee (HTTP PUT method):</h3> http://localhost:8080/SpringRSWebService/services/updateEmp/ 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 <a rel="nofollow" href="https://addons.mozilla.org/en-us/firefox/addon/restclient/">REST Client add-on for Firefox</a. or the <a rel="nofollow" href="http://www.code.google.com/p/rest-client/">Java based REST client application</a>. 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: <blockquote> http://springrswebservice.extremejava.cloudbees.net/services/getEmp/1 http://springrswebservice.extremejava.cloudbees.net/services/addEmp (use RESTClient for adding body) http://springrswebservice.extremejava.cloudbees.net/services/removeEmp/1 http://springrswebservice.extremejava.cloudbees.net/services/updateEmp/1 (use RESTClient for adding body) </blockquote> The complete code for this application in zip format can be downloaded from link given below: <div class="download-code"><img src="http://www.javaexperience.com/wp-content/uploads/2012/12/downloadcode-e13492789421641.jpg"><a href="http://javaexperience.com/wp-content/uploads/2012/12/SpringRSWebService.zip"><br><br><strong>Spring RESTful web service</strong></a></div>
Alternatives to ApplicationContext.getBean
Modularize Spring application
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Latest posts by admin (see all)

Comments

comments