Spring Rest Service CRUD operations with XML


CRUD stands for Create,Read,Update and Delete operation

These are the most common operations that we perform in any application.

CRUD_operation_JAXB_Table

Let’s do these operations using Spring Rest service.

Requirement :

Perform CRUD operations on USER object.

We have User Domain object, we can insert User data, read the inserted data,

Update some user information and finally delete the user data.

Create a new Maven Web project in eclipse (Refer Spring MVC Hello World project for the same)

Project structure


rest_spring_crud_xml_proj_structure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>SpringRestCRUDXML</groupId>
  5.   <artifactId>SpringRestCRUDXML</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringRestCRUDXML Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.     <dependencies>
  14.         <dependency>
  15.             <groupId>junit</groupId>
  16.             <artifactId>junit</artifactId>
  17.             <version>3.8.1</version>
  18.             <scope>test</scope>
  19.         </dependency>
  20.         <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.     </dependencies>
  32.   <build>
  33.     <finalName>SpringRestCRUDXML</finalName>
  34.   </build>
  35. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringRestCRUDXML</groupId>
  <artifactId>SpringRestCRUDXML</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestCRUDXML Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
	</dependencies>
  <build>
    <finalName>SpringRestCRUDXML</finalName>
  </build>
</project>

We have added dependencies for Spring web ,spring web mvc and Junit in the above pom file.

Step 2

Update web.xml file with Dispatcher servlet

we have defined a dispatcher servlet in web.xml and mapped it by the URL pattern “/”

So just like any other servlet in web application,any request matching with the given pattern i.e “/” will be redirected to “Dispatcher servlet”.

  1. <web-app id="WebApp_ID" version="2.4"
  2.     xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  4. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  5.  
  6.     <display-name>Archetype Created Web Application</display-name>
  7.     <servlet>
  8.         <servlet-name>mvc-dispatcher</servlet-name>
  9.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10.         <init-param>
  11.             <param-name>contextConfigLocation</param-name>
  12.             <param-value>
  13.             /WEB-INF/spring-mvc.xml
  14.             </param-value>
  15.         </init-param>
  16.         <load-on-startup>1</load-on-startup>
  17.     </servlet>
  18.  
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <context-param>
  25.         <param-name>contextConfigLocation</param-name>
  26.         <param-value>/WEB-INF/spring-mvc.xml</param-value>
  27.     </context-param>
  28.  
  29.     <listener>
  30.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  31.     </listener>
  32. </web-app>
<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>Archetype Created Web Application</display-name>
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
            /WEB-INF/spring-mvc.xml
            </param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-mvc.xml</param-value>
	</context-param>

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

We have also provided the spring configuration file name to create and load the spring beans while starting the server.

Step 3

Create a domain class which represents the data in XML format

We will perform CRUD operations on this object.

User.java

  1. package com.kb.rest.model;
  2.  
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7.  
  8. @XmlRootElement(name="User")
  9. @XmlAccessorType(XmlAccessType.FIELD)
  10. public class User {
  11.     @XmlElement
  12.     private String name;
  13.     @XmlElement
  14.     private int age;
  15.     @XmlElement
  16.     private int id;
  17.     public String getName() {
  18.         return name;
  19.     }
  20.     public void setName(String name) {
  21.         this.name = name;
  22.     }
  23.     public int getAge() {
  24.         return age;
  25.     }
  26.     public void setAge(int age) {
  27.         this.age = age;
  28.     }
  29.     public int getId() {
  30.         return id;
  31.     }
  32.     public void setId(int id) {
  33.         this.id = id;
  34.     }
  35. }
package com.kb.rest.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="User")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
	@XmlElement
	private String name;
	@XmlElement
	private int age;
	@XmlElement
	private int id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
}

We have created a User class with id,name and age to represent the data

@XmlRootElement – specifies the root tag of each user record in xml.

@XmlElement – specifies the child element for each attribute of User record.

UserList.java

  1. package com.kb.rest.model;
  2.  
  3. import java.util.List;
  4.  
  5. import javax.xml.bind.annotation.XmlAccessType;
  6. import javax.xml.bind.annotation.XmlAccessorType;
  7. import javax.xml.bind.annotation.XmlElement;
  8. import javax.xml.bind.annotation.XmlRootElement;
  9.  
  10. @XmlRootElement(name="UserList")
  11. @XmlAccessorType(XmlAccessType.FIELD)
  12. public class UserList {
  13.    
  14.     @XmlElement(name="User")
  15.     private List<User> userList;
  16.  
  17.     public List<User> getUserList() {
  18.         return userList;
  19.     }
  20.  
  21.     public void setUserList(List<User> userList) {
  22.         this.userList = userList;
  23.     }
  24.  
  25. }
package com.kb.rest.model;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="UserList")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserList {
	
	@XmlElement(name="User")
	private List<User> userList;

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

}

we have created UserList class with one attribute for List of User object.

Why do We need to create UserList class ?

Whenever we need to return list of objects as a XML response , it does not directly supports it.
We have to specify how our List should look like.
So In our Rest service,we are returning a List of all the users in getAllUsers API , hence we have to write a JAXB class for the same.

Step 4

Create the resource mapping class which will have the URL mapping methods for all our CRUD operations

  1. package com.kb.rest.controllers;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13.  
  14. import com.kb.rest.model.User;
  15. import com.kb.rest.model.UserList;
  16. import com.kb.rest.service.UserService;
  17.  
  18. @Controller
  19. @RequestMapping("/user")
  20. public class RestController {
  21.  
  22.     @Autowired
  23.     private UserService userService;
  24.    
  25.     // CRUD -- CREATE operation
  26.     @RequestMapping(value = "/create", method = RequestMethod.POST)
  27.     public @ResponseBody User createUser(@RequestBody User user) {
  28.         User userResponse = userService.createUser(user);
  29.         return userResponse;
  30.     }
  31.  
  32.     // CRUD -- READ operation
  33.     @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
  34.     public @ResponseBody UserList getAllUsers() {
  35.         List<User> userList = userService.getAllUsers();
  36.         UserList userListCustom = new UserList();
  37.         userListCustom.setUserList(userList);
  38.         return userListCustom;
  39.     }
  40.  
  41.     // CRUD -- READ operation
  42.     @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
  43.     public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
  44.         User user = userService.getUserForId(id);
  45.         return user;
  46.     }
  47.  
  48.     // CRUD -- UPDATE operation
  49.     @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
  50.     public @ResponseBody User updateUser(@RequestBody User user) {
  51.         User userResponse = userService.updateUser(user);
  52.         return userResponse;
  53.     }
  54.  
  55.     // CRUD -- DELETE operation
  56.     @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
  57.     public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
  58.         User userResponse = userService.deleteUser(id);
  59.         return userResponse;
  60.     }
  61. }
package com.kb.rest.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.kb.rest.model.User;
import com.kb.rest.model.UserList;
import com.kb.rest.service.UserService;

@Controller
@RequestMapping("/user")
public class RestController {

	@Autowired
	private UserService userService;
	
	// CRUD -- CREATE operation
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody User createUser(@RequestBody User user) {
		User userResponse = userService.createUser(user);
		return userResponse;
	}

	// CRUD -- READ operation
	@RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
	public @ResponseBody UserList getAllUsers() {
		List<User> userList = userService.getAllUsers();
		UserList userListCustom = new UserList();
		userListCustom.setUserList(userList);
		return userListCustom;
	}

	// CRUD -- READ operation
	@RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET)
	public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
		User user = userService.getUserForId(id);
		return user;
	}

	// CRUD -- UPDATE operation
	@RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
	public @ResponseBody User updateUser(@RequestBody User user) {
		User userResponse = userService.updateUser(user);
		return userResponse;
	}

	// CRUD -- DELETE operation
	@RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE)
	public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
		User userResponse = userService.deleteUser(id);
		return userResponse;
	}
}

We have created the Controller class above which will act as a Rest service in Spring.

How Spring controller acts as a Rest service ?

We have @ResponseBody before the return type of a method in method signature which indicates to Spring that ,the returned value from this method will not be a view rather it has to be read from the response body.

We have @RequestBody as a method parameter in POST and PUT methods, which indicates to Spring that ,the passed value for this request method will be from the Request Body

Hence any one can call this method with the appropriate end point

@PathVariable :
It is used to get the parameter value passed along with the URL.
Its very similar to @PathParam in JAX-RS.

@PathVariable(“id”) int id
This will get the value passed in the URL and inject it to id variable of method argument.

Possible end points for the above CRUD operations are as below

Request MethodEnd pointDescription
GEThttp://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/3Get user based on ID(which is 3 in this case)
GEThttp://localhost:8080/SpringRestCRUDXML/user/ getAllUsersGet all the Users
POSThttp://localhost:8080/SpringRestCRUDXML/user/createCreate new User record and store it
PUThttp://localhost:8080/SpringRestCRUDXML/user/updateUserUpdate the user object
DELETEhttp://localhost:8080/SpringRestCRUDXML/user/deleteUser/3Delete the user object with id 3

We can also use @RestController directly instead of @Controller, in that case we don’t need to use @ResponseBody in each method.

@RestController=@Controller + @ResponseBody

Note: @RestController is supported in Spring 4 and above

Step 5

Create the business service class

  1. package com.kb.rest.service;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import com.kb.rest.dao.UserDAO;
  9. import com.kb.rest.model.User;
  10.  
  11. @Service
  12. public class UserService {
  13.    
  14.     @Autowired
  15.     private UserDAO userDao;
  16.  
  17.     public List<User> getAllUsers() {
  18.         List<User> userList = userDao.getAllUsers();
  19.         return userList;
  20.     }
  21.  
  22.     public User getUserForId(int id) {
  23.         User user = userDao.getUserForId(id);
  24.         return user;
  25.     }
  26.  
  27.     public User createUser(User user) {
  28.         User userResponse = userDao.createUser(user);
  29.         return userResponse;
  30.     }
  31.  
  32.     public User updateUser(User user) {
  33.         User userResponse = userDao.updateUser(user);
  34.         return userResponse;
  35.     }
  36.  
  37.     public User deleteUser(int id) {
  38.         User userResponse = userDao.deleteUser(id);
  39.         return userResponse;
  40.     }
  41.  
  42. }
package com.kb.rest.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kb.rest.dao.UserDAO;
import com.kb.rest.model.User;

@Service
public class UserService {
	
	@Autowired
	private UserDAO userDao;

	public List<User> getAllUsers() {
		List<User> userList = userDao.getAllUsers();
		return userList;
	}

	public User getUserForId(int id) {
		User user = userDao.getUserForId(id);
		return user;
	}

	public User createUser(User user) {
		User userResponse = userDao.createUser(user);
		return userResponse;
	}

	public User updateUser(User user) {
		User userResponse = userDao.updateUser(user);
		return userResponse;
	}

	public User deleteUser(int id) {
		User userResponse = userDao.deleteUser(id);
		return userResponse;
	}

}

We have defined 5 methods in the above class

getAllUsers() – This method is used to get all the users, helps to serve GET request

getUserForId(String id) – This method is used to get the user details for a specific user,helps to serve the GET request for a specific user

createUser(User user) – This method is used to insert the new user details,helps to serve the POST request

updateUser(User user) – This method is used to update the user details,helps to serve the PUT request

deleteUser(String id) – This method is used to delete the user details,helps to serve the DELETE request

Step 6

Create the DAO class

  1. package com.kb.rest.dao;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6.  
  7. import org.springframework.stereotype.Repository;
  8.  
  9. import com.kb.rest.model.User;
  10.  
  11. //Just to avoid DB calls in this example, Assume below data is interacting with DB
  12.  
  13. @Repository
  14. public class UserDAO {
  15.     static HashMap<Integer, User> usersMap = new HashMap<Integer, User>();
  16.  
  17.     public UserDAO() {
  18.             User user1 = new User();
  19.             user1.setId(1);
  20.             user1.setAge(20);
  21.             user1.setName("raj");
  22.            
  23.             User user2 = new User();
  24.             user2.setId(2);
  25.             user2.setAge(21);
  26.             user2.setName("ram");
  27.            
  28.             usersMap.put(1, user1);
  29.             usersMap.put(2, user2);
  30.     }
  31.  
  32.     public List<User> getAllUsers() {
  33.  
  34.         List<User> userList = new ArrayList<User>(usersMap.values());
  35.         return userList;
  36.     }
  37.  
  38.     public User getUserForId(int id) {
  39.         User user = usersMap.get(id);
  40.         return user;
  41.     }
  42.  
  43.     public User createUser(User user) {
  44.         usersMap.put(user.getId(), user);
  45.         return usersMap.get(user.getId());
  46.     }
  47.  
  48.     public User updateUser(User user) {
  49.         if (usersMap.get(user.getId()) != null) {
  50.             usersMap.get(user.getId()).setName(user.getName());
  51.         } else {
  52.             usersMap.put(user.getId(), user);
  53.         }
  54.         return usersMap.get(user.getId());
  55.     }
  56.  
  57.     public User deleteUser(int id) {
  58.         User userResponse = usersMap.remove(id);
  59.         return userResponse;
  60.     }
  61.  
  62. }
package com.kb.rest.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.kb.rest.model.User;

//Just to avoid DB calls in this example, Assume below data is interacting with DB

@Repository
public class UserDAO {
	static HashMap<Integer, User> usersMap = new HashMap<Integer, User>();

	public UserDAO() {
			User user1 = new User();
			user1.setId(1);
			user1.setAge(20);
			user1.setName("raj");
			
			User user2 = new User();
			user2.setId(2);
			user2.setAge(21);
			user2.setName("ram");
			
			usersMap.put(1, user1);
			usersMap.put(2, user2);
	}

	public List<User> getAllUsers() {

		List<User> userList = new ArrayList<User>(usersMap.values());
		return userList;
	}

	public User getUserForId(int id) {
		User user = usersMap.get(id);
		return user;
	}

	public User createUser(User user) {
		usersMap.put(user.getId(), user);
		return usersMap.get(user.getId());
	}

	public User updateUser(User user) {
		if (usersMap.get(user.getId()) != null) {
			usersMap.get(user.getId()).setName(user.getName());
		} else {
			usersMap.put(user.getId(), user);
		}
		return usersMap.get(user.getId());
	}

	public User deleteUser(int id) {
		User userResponse = usersMap.remove(id);
		return userResponse;
	}

}

We have created DAO class to support all the CRUD operations

We have used a usersMap to store user details(just to avoid DB interaction)

In the constructor , we have added 2 user details in the userMap.

and all the other methods will use this userMap to read,insert,update and delete the user details.

Step 7

Build and deploy the project

Step 8

Let’s see the output of all CRUD operations by using Advanced Rest client

POST


http://localhost:8080/SpringRestCRUDXML/user/create

Select content type “application/xml

Request body

  1. <User>
  2. <name>John</name>
  3.  <age>45</age>
  4.  <id>3</id>
  5.  </User>
<User>
<name>John</name>
 <age>45</age>
 <id>3</id>
 </User>

Select POST method

rest_spring_crud_xml_post

We can see 200 status in the response.

GET


http://localhost:8080/SpringRestCRUDXML/user/getAllUsers

Select GET method

rest_spring_crud_xml_getAll

GET with specific user ID


http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/1

Select GET method

rest_spring_crud_xml_getSpecific

PUT


http://localhost:8080/SpringRestCRUDXML/user/updateUser

Select content type “application/xml

Request body

  1. <User>
  2. <name>John</name>
  3.  <age>45</age>
  4.  <id>1</id>
  5.  </User>
<User>
<name>John</name>
 <age>45</age>
 <id>1</id>
 </User>

Select PUT method

rest_spring_crud_xml_put

We can see 200 status in the response.

DELETE


http://localhost:8080/SpringRestCRUDXML/user/deleteUser/3

Select DELETE method

rest_spring_crud_xml_delete

Now try to fetch this record using GET to verify whether it’s deleted or not

http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/3

rest_spring_crud_xml_delete_get

We can see the record got deleted.

Download this project SpringRestCRUDXML.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on