CRUD operations with JAX-RS and JSON


Rest Service CRUD operations using JAX-RS with JSON and Jersey


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 Rest service with Jersey and JSON.

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 Rest service Hello World project for the same)


Project structure

Rest_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>CRUDWithRestAndJson</groupId>
  5.   <artifactId>CRUDWithRestAndJson</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>CRUDWithRestAndJson Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <dependencies>
  11.     <dependency>
  12.       <groupId>junit</groupId>
  13.       <artifactId>junit</artifactId>
  14.       <version>3.8.1</version>
  15.       <scope>test</scope>
  16.     </dependency>
  17.   <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
  18. <dependency>
  19.     <groupId>org.glassfish.jersey.media</groupId>
  20.     <artifactId>jersey-media-moxy</artifactId>
  21.     <version>2.25</version>
  22. </dependency>
  23.  <dependency>
  24.     <groupId>org.glassfish.jersey.containers</groupId>
  25.     <artifactId>jersey-container-servlet</artifactId>
  26.     <version>2.24</version>
  27. </dependency>
  28.  
  29.   </dependencies>
  30.   <build>
  31.     <finalName>CRUDWithRestAndJson</finalName>
  32.   </build>
  33. </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>CRUDWithRestAndJson</groupId>
  <artifactId>CRUDWithRestAndJson</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>CRUDWithRestAndJson Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.25</version>
</dependency>
 <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.24</version>
</dependency>

  </dependencies>
  <build>
    <finalName>CRUDWithRestAndJson</finalName>
  </build>
</project>

We have added dependencies for Jersey servlet,jersey-media-moxy and Junit in the above pom file.
jersey-media-moxy dependency is used for automatic JSON support without any other configuration.

Step 2

Update web.xml file with Jersey servlet container

we have defined a special servlet called “jersey-serlvet” in web.xml and mapped it by the URL pattern /rest/*

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

  1. <!DOCTYPE web-app PUBLIC
  2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4.  
  5. <web-app>
  6.   <display-name>Archetype Created Web Application</display-name>
  7.   <servlet>
  8.         <servlet-name>jersey-serlvet</servlet-name>
  9.          <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  10.         <init-param>
  11.             <param-name>jersey.config.server.provider.packages</param-name>
  12.             <param-value>com.kb.rest.resource</param-value>
  13.         </init-param>
  14.         <load-on-startup>1</load-on-startup>
  15.     </servlet>
  16.  
  17.     <servlet-mapping>
  18.         <servlet-name>jersey-serlvet</servlet-name>
  19.         <url-pattern>/rest/*</url-pattern>
  20.     </servlet-mapping>
  21. </web-app>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.kb.rest.resource</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

We have also provided the package of java classes(to be qualified as Rest services) under init-param tag.

This package will be considered by Jersey servlet container to identify the actual service when the request comes in.

Step 3

Create a domain class which represents the data

We will perform CRUD operations on this object.

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

public class User {
	private String id;
	private String name;
	private int age;
	public String getId() {
		return id;
	}
	
	public void setId(String id) {
		this.id = 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;
	}
}

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

This object will be converted to JSON and back to Object from Jersey JSON support

Step 4

Create the resource mapping class which will have the URL mapping methods

  1. package com.kb.rest.resource;
  2.  
  3. import java.util.List;
  4.  
  5. import javax.ws.rs.Consumes;
  6. import javax.ws.rs.DELETE;
  7. import javax.ws.rs.GET;
  8. import javax.ws.rs.POST;
  9. import javax.ws.rs.PUT;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.PathParam;
  12. import javax.ws.rs.Produces;
  13. import javax.ws.rs.core.MediaType;
  14.  
  15. import com.kb.model.User;
  16. import com.kb.service.UserService;
  17.  
  18. @Path("/userInfo")
  19. public class UserResource {
  20.     UserService userService = new UserService();
  21.  
  22.     // CRUD -- CREATE operation
  23.     @POST
  24.     @Produces(MediaType.APPLICATION_JSON)
  25.     @Consumes(MediaType.APPLICATION_JSON)
  26.     public User createUser(User user) {
  27.         User userResponse = userService.createUser(user);
  28.         return userResponse;
  29.     }
  30.  
  31.     // CRUD -- READ operation
  32.     @GET
  33.     @Produces(MediaType.APPLICATION_JSON)
  34.     public List<User> getAllUsers() {
  35.         List<User> userList = userService.getAllUsers();
  36.         return userList;
  37.     }
  38.  
  39.     // CRUD -- READ operation
  40.     @GET
  41.     @Path("/{id}")
  42.     @Produces(MediaType.APPLICATION_JSON)
  43.     public User getUserForId(@PathParam("id") String id) {
  44.         User user = userService.getUserForId(id);
  45.         return user;
  46.     }
  47.  
  48.     // CRUD -- UPDATE operation
  49.     @PUT
  50.     @Produces(MediaType.APPLICATION_JSON)
  51.     @Consumes(MediaType.APPLICATION_JSON)
  52.     public User updateUser(User user) {
  53.         User userResponse = userService.updateUser(user);
  54.         return userResponse;
  55.     }
  56.  
  57.     // CRUD -- DELETE operation
  58.     @DELETE
  59.     @Path("/{id}")
  60.     @Produces(MediaType.APPLICATION_JSON)
  61.     public User deleteeUser(@PathParam("id") String id) {
  62.         User userResponse = userService.deleteUser(id);
  63.         return userResponse;
  64.     }
  65. }
package com.kb.rest.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.kb.model.User;
import com.kb.service.UserService;

@Path("/userInfo")
public class UserResource {
	UserService userService = new UserService();

	// CRUD -- CREATE operation
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public User createUser(User user) {
		User userResponse = userService.createUser(user);
		return userResponse;
	}

	// CRUD -- READ operation
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<User> getAllUsers() {
		List<User> userList = userService.getAllUsers();
		return userList;
	}

	// CRUD -- READ operation
	@GET
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public User getUserForId(@PathParam("id") String id) {
		User user = userService.getUserForId(id);
		return user;
	}

	// CRUD -- UPDATE operation
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public User updateUser(User user) {
		User userResponse = userService.updateUser(user);
		return userResponse;
	}

	// CRUD -- DELETE operation
	@DELETE
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public User deleteeUser(@PathParam("id") String id) {
		User userResponse = userService.deleteUser(id);
		return userResponse;
	}
}

We have created the Rest service class above which will handle GET,POST,PUT and DELETE operations

@Path(“/userInfo”)

This annotation helps to map the request URL to the appropriate Rest service.
So any request with /userInfo (relative to the base URL) will be mapped to UserResource.

@POST

This annotation specifies that only POST requests will be accepted by this method.

@GET

This annotation specifies that only GET requests will be accepted by this method

@PUT

This annotation specifies that only PUT requests will be accepted by this method

@DELETE

This annotation specifies that only DELETE requests will be accepted by this method.

@Path(“/{id}”)

This annotation is used to specify that URL will contain input value to match exactly.
read more on Path variables here

@Produces(MediaType.APPLICATION_JSON)


This annotation is used to specify the representation of a data (MIME type) that the service can produce and send it to client.

This annotation can be used either at the class level or at the method level.

If this annotation is applied at the class level,all the methods in the class can produce the same MIME type data by default.

However we can override this at the method level with different MIME type.

We can also specify multiple MIME types as below@Produces({“application/xml”, “application/json”})

@Consumes(MediaType.APPLICATION_JSON)


This annotation is used to specify the representation of a data (MIME type) that the service can accept from the client.

This annotation can be used either at the class level or at the method level.

If this annotation is applied at the class level,all the methods in the class will accept the same MIME type data from client by default.

However we can override this at the method level with different MIME type.

We can also specify multiple MIME types as below@Consumes({“application/xml”, “application/json”})

Step 5

Create the business service class

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.dao.UserDAO;
  6. import com.kb.model.User;
  7.  
  8. public class UserService {
  9.     UserDAO userDao = new UserDAO();
  10.  
  11.     public List<User> getAllUsers() {
  12.         List<User> userList = userDao.getAllUsers();
  13.         return userList;
  14.     }
  15.  
  16.     public User getUserForId(String id) {
  17.         User user = userDao.getUserForId(id);
  18.         return user;
  19.     }
  20.  
  21.     public User createUser(User user) {
  22.         User userResponse = userDao.createUser(user);
  23.         return userResponse;
  24.     }
  25.  
  26.     public User updateUser(User user) {
  27.         User userResponse = userDao.updateUser(user);
  28.         return userResponse;
  29.     }
  30.  
  31.     public User deleteUser(String id) {
  32.         User userResponse = userDao.deleteUser(id);
  33.         return userResponse;
  34.     }
  35.  
  36. }
package com.kb.service;

import java.util.List;

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

public class UserService {
	UserDAO userDao = new UserDAO();

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

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

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

import com.kb.model.User;

//Just to avoid DB calls in this example, Assume below data is interacting with DB
public class UserDAO {
	static HashMap<String, User> usersMap = new HashMap<String, 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(String 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(String 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

url:
http://localhost:8080/CRUDWithRestAndJson/rest/userInfo

Select content type “application/json

Request body

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

Select POST method

Rest_crud_json_post_1

We can see 200 status in the response.

GET

url:
http://localhost:8080/CRUDWithRestAndJson/rest/userInfo

Select GET method

Rest_crud_json_get

GET with specific user ID

url:
http://localhost:8080/CRUDWithRestAndJson/rest/userInfo/1

Select GET method

Rest_crud_json_get_specific_id

PUT

url:
http://localhost:8080/CRUDWithRestAndJson/rest/userInfo

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_crud_json_put_1

We can see 200 status in the response.

DELETE

url:
http://localhost:8080/CRUDWithRestAndJson/rest/userInfo/3

Select DELETE method

Rest_crud_json_delete_1

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

Rest_crud_json_delete_2

We can see the record got deleted.

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