Spring Rest Service CRUD operations with JSON


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_json_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>SpringRestCRUDJSON</groupId>
  5.     <artifactId>SpringRestCRUDJSON</artifactId>
  6.     <packaging>war</packaging>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <name>SpringRestCRUDJSON 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.         <!-- Jackson JSON -->
  32.         <dependency>
  33.             <groupId>com.fasterxml.jackson.core</groupId>
  34.             <artifactId>jackson-databind</artifactId>
  35.             <version>2.8.5</version>
  36.         </dependency>
  37.     </dependencies>
  38.     <build>
  39.         <finalName>SpringRestCRUDJSON</finalName>
  40.     </build>
  41. </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>SpringRestCRUDJSON</groupId>
	<artifactId>SpringRestCRUDJSON</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringRestCRUDJSON 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>
		<!-- Jackson JSON -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringRestCRUDJSON</finalName>
	</build>
</project>

We have added dependencies for Spring web ,spring web mvc,Jackson 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 JSON format

We will perform CRUD operations on this object.

  1. package com.kb.rest.model;
  2.  
  3. public class User {
  4.     private String name;
  5.     private int age;
  6.     private int id;
  7.     public String getName() {
  8.         return name;
  9.     }
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.     public void setAge(int age) {
  17.         this.age = age;
  18.     }
  19.     public int getId() {
  20.         return id;
  21.     }
  22.     public void setId(int id) {
  23.         this.id = id;
  24.     }
  25.  
  26. }
package com.kb.rest.model;

public class User {
	private String name;
	private int age;
	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

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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.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(User user) {
		User userResponse = userService.createUser(user);
		return userResponse;
	}

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

	// 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(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.

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 Method End point Description
GEThttp://localhost:8080/SpringRestCRUDJSON/user/getSpecificUser/3Get user based on ID(which is 3 in this case)
GEThttp://localhost:8080/SpringRestCRUDJSON/user/ getAllUsersGet all the users
POSThttp://localhost:8080/SpringRestCRUDJSON/user/createCreate new User record and store it
PUThttp://localhost:8080/SpringRestCRUDJSON/user/updateUserUpdate the user object
DELETEhttp://localhost:8080/SpringRestCRUDJSON/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/SpringRestCRUDJSON/user/create

Select content type “application/json

Request body

  1. {
  2. "age": 30,
  3. "id": 3,
  4. "name": "John"
  5. }
{
"age": 30,
"id": 3,
"name": "John"
}

Select POST method

rest_spring_crud_json_post

We can see 200 status in the response.

GET


http://localhost:8080/SpringRestCRUDJSON/user/getAllUsers

Select GET method

rest_spring_crud_json_getAll

GET with specific user ID


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

Select GET method

rest_spring_crud_json_getSpecific

PUT


http://localhost:8080/SpringRestCRUDJSON/user/updateUser

Select content type “application/json

Request body

  1. {
  2. "age": 30,
  3. "id": "3",
  4. "name": "John"
  5. }
{
"age": 30,
"id": "3",
"name": "John"
}

Select PUT method

rest_spring_crud_json_put

We can see 200 status in the response.

DELETE


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

Select DELETE method

rest_spring_crud_json_delete

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

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

rest_spring_crud_json_delete_get

We can see the record got deleted.

Download this project SpringRestCRUDJSON.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