Rest service CRUD operations with JSP and ajax


In the previous article, we have seen CRUD operations in Rest service with Advanced rest client
Let’s do the same using JSP page and ajax as a client


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)

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4.         http://maven.apache.org/maven-v4_0_0.xsd">
  5.   <modelVersion>4.0.0</modelVersion>
  6.   <groupId>CRUDWithRestAndJSP</groupId>
  7.   <artifactId>CRUDWithRestAndJSP</artifactId>
  8.   <packaging>war</packaging>
  9.   <version>0.0.1-SNAPSHOT</version>
  10.   <name>CRUDWithRestAndJSP Maven Webapp</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  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.    
  21.       <dependency>
  22.               <groupId>junit</groupId>
  23.               <artifactId>junit</artifactId>
  24.               <version>3.8.1</version>
  25.               <scope>test</scope>
  26.       </dependency>
  27.  
  28.       <dependency>
  29.               <groupId>org.glassfish.jersey.containers</groupId>
  30.               <artifactId>jersey-container-servlet</artifactId>
  31.               <version>2.24</version>
  32.       </dependency>
  33.  
  34.       <dependency>
  35.               <groupId>javax.xml</groupId>
  36.               <artifactId>jaxb-api</artifactId>
  37.               <version>2.1</version>
  38.       </dependency>
  39.  
  40.       <dependency>
  41.               <groupId>javax.servlet</groupId>
  42.               <artifactId>servlet-api</artifactId>
  43.               <version>2.5</version>
  44.       </dependency>
  45.  
  46.       <dependency>
  47.               <groupId>org.webjars</groupId>
  48.               <artifactId>jquery</artifactId>
  49.               <version>2.1.4</version>
  50.       </dependency>
  51.  
  52.   </dependencies>
  53.  
  54.  <build>
  55.     <finalName>CRUDWithRestAndJSP</finalName>
  56.  </build>
  57.  
  58. </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>CRUDWithRestAndJSP</groupId>
  <artifactId>CRUDWithRestAndJSP</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>CRUDWithRestAndJSP 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>
    
      <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>3.8.1</version>
              <scope>test</scope>
      </dependency>
 
      <dependency>
              <groupId>org.glassfish.jersey.containers</groupId>
              <artifactId>jersey-container-servlet</artifactId>
              <version>2.24</version>
      </dependency>

      <dependency>
              <groupId>javax.xml</groupId>
              <artifactId>jaxb-api</artifactId>
              <version>2.1</version>
      </dependency>

      <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>servlet-api</artifactId>
              <version>2.5</version>
      </dependency>

      <dependency>
              <groupId>org.webjars</groupId>
              <artifactId>jquery</artifactId>
              <version>2.1.4</version>
      </dependency>

  </dependencies>
 
 <build>
    <finalName>CRUDWithRestAndJSP</finalName>
 </build>

</project>

We have added dependencies for Jersey servlet,Jaxb,servelt api , jquery and Junit in the above pom file.

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 with JAXB

We will perform CRUD operations on this object.

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

import java.util.Date;

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

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

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.

Create the UI pages for CRUD operations


Step 4

Create a home page which can display the links for each of the CRUD operation.

Index.jsp

  1. <!DOCTYPE html>
  2. <%@ page isELIgnored="false" %>
  3. <html>
  4. <head>
  5. <title>Create User</title>
  6. </head>
  7. <body>
  8.     <div style="padding-left:50px;font-family:monospace;">
  9.             CRUD Operations</br></br>
  10.         <a href="${pageContext.request.contextPath}/create.jsp"><div
  11.                                 style="color:saffron">Create User</div></a></br></br>
  12.         <a href="${pageContext.request.contextPath}/rest/userInfo"><div
  13.                                 style="color:saffron">Get User details</div></a></br></br>
  14.         <a href="${pageContext.request.contextPath}/update.jsp"><div
  15.                                 style="color:saffron">Update User</div></a></br></br>
  16.         <a href="${pageContext.request.contextPath}/delete.jsp"><div
  17.                                 style="color:saffron">Delete User</div></a></br></br>
  18.     </div>
  19. </body>
  20. </html>
<!DOCTYPE html>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Create User</title>
</head>
<body>
	<div style="padding-left:50px;font-family:monospace;">
			CRUD Operations</br></br>
		<a href="${pageContext.request.contextPath}/create.jsp"><div 
                                style="color:saffron">Create User</div></a></br></br>
		<a href="${pageContext.request.contextPath}/rest/userInfo"><div 
                                style="color:saffron">Get User details</div></a></br></br>
		<a href="${pageContext.request.contextPath}/update.jsp"><div 
                                style="color:saffron">Update User</div></a></br></br>
		<a href="${pageContext.request.contextPath}/delete.jsp"><div 
                                style="color:saffron">Delete User</div></a></br></br>
	</div>
</body>
</html>

This page contains the hyperlinks to perform various CRUD operations.

Step 5

Create the JSP page for creating a new user(POST method)

Create.jsp

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Create User</title>
  5. </head>
  6. <body>
  7.     <div style="padding-left:50px;font-family:monospace;">
  8.         <h2>Create User</h2>
  9.         <form action="rest/userInfo" method="POST">
  10.             <div style="width: 100px; text-align:left;">
  11.                 <div style="padding:15px;">
  12.                     User ID: <input name="id" />
  13.                 </div>
  14.                 <div style="padding:10px;">
  15.                     Name: <input name="name" />
  16.                 </div>
  17.                 <div style="padding:10px;">
  18.                     Age: <input name="age" />
  19.                 </div>
  20.                 <div style="padding:20px;text-align:center">
  21.                     <input type="submit" value="Submit" />
  22.                 </div>
  23.             </div>
  24.         </form>
  25.     </div>
  26. </body>
  27. </html>
<!DOCTYPE html>
<html>
<head>
<title>Create User</title>
</head>
<body>
	<div style="padding-left:50px;font-family:monospace;">
		<h2>Create User</h2>
		<form action="rest/userInfo" method="POST">
			<div style="width: 100px; text-align:left;">
				<div style="padding:15px;">
					User ID: <input name="id" />
				</div>
				<div style="padding:10px;">
					Name: <input name="name" />
				</div>
				<div style="padding:10px;">
					Age: <input name="age" />
				</div>
				<div style="padding:20px;text-align:center">
					<input type="submit" value="Submit" />
				</div>
			</div>
		</form>
	</div>
</body>
</html>


Step 6

Create the JSP page for updating the user(PUT method)

update.jsp

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  4. <script src="js/rest.js"></script>
  5. <%@ page contentType="text/html; charset=UTF-8" %>
  6. <head>
  7. <title>Update User</title>
  8. </head>
  9. <body>
  10.     <div style="padding-left:50px;font-family:monospace;">
  11.         <h2>Update User</h2>
  12.         <form id="updateForm">
  13.             <div style="width: 100px; text-align:left;">
  14.                 <div style="padding:15px;">
  15.                     User ID: <input name="id" />
  16.                 </div>
  17.                 <div style="padding:10px;">
  18.                     Name: <input name="name" />
  19.                 </div>
  20.                 <div style="padding:10px;">
  21.                     Age: <input name="age" />
  22.                 </div>
  23.                 <div style="padding:20px;text-align:center">
  24.                     <input type="submit" value="Submit" />
  25.                 </div>
  26.             </div>
  27.         </form>
  28.     </div>
  29. </body>
  30. </html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="js/rest.js"></script>
<%@ page contentType="text/html; charset=UTF-8" %>
<head>
<title>Update User</title>
</head>
<body>
	<div style="padding-left:50px;font-family:monospace;">
		<h2>Update User</h2>
		<form id="updateForm">
			<div style="width: 100px; text-align:left;">
				<div style="padding:15px;">
					User ID: <input name="id" />
				</div>
				<div style="padding:10px;">
					Name: <input name="name" />
				</div>
				<div style="padding:10px;">
					Age: <input name="age" />
				</div>
				<div style="padding:20px;text-align:center">
					<input type="submit" value="Submit" />
				</div>
			</div>
		</form>
	</div>
</body>
</html>


Step 7

Create the JSP page for Deleting the user(DELETE method)

delete.jsp

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  4. <script src="js/rest.js"></script>
  5. <%@ page contentType="text/html; charset=UTF-8" %>
  6. <head>
  7. <title>Delete User</title>
  8. </head>
  9. <body>
  10.     <div style="padding-left:50px;font-family:monospace;">
  11.         <h2>Delete User</h2>
  12.         <form id="deleteForm">
  13.             <div style="width: 100px; text-align:left;">
  14.                 <div style="padding:15px;">
  15.                     User ID: <input name="id" />
  16.                 </div>
  17.                 <div style="padding:20px;text-align:center">
  18.                     <input type="submit" value="Submit" />
  19.                 </div>
  20.             </div>
  21.         </form>
  22.     </div>
  23. </body>
  24. </html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="js/rest.js"></script>
<%@ page contentType="text/html; charset=UTF-8" %>
<head>
<title>Delete User</title>
</head>
<body>
	<div style="padding-left:50px;font-family:monospace;">
		<h2>Delete User</h2>
		<form id="deleteForm">
			<div style="width: 100px; text-align:left;">
				<div style="padding:15px;">
					User ID: <input name="id" />
				</div>
				<div style="padding:20px;text-align:center">
					<input type="submit" value="Submit" />
				</div>
			</div>
		</form>
	</div>
</body>
</html>


Step 8

Create the java script file to perform ajax operation on PUT and DELETE operations.

Note

Form submission supports only GET and POST , hence using ajax call to perform PUT and DELETE operations.

rest.js

  1. $(document).ready(function () {
  2.  
  3. $("#updateForm").on("submit", function(){
  4.    
  5.     $.ajax({
  6.         url: 'rest/userInfo',
  7.         type: 'PUT',
  8.         dataType: "xml",
  9.         data:$("#updateForm").serialize(),
  10.         success: function(xml) {
  11.             console.log(xml);
  12.             var user="";
  13.             $(xml).find('User').each(function(){
  14.                 $(this).find("id").each(function(){
  15.                     var id = $(this).text();
  16.                     console.log(id);
  17.                     user=user+"ID: "+id;
  18.                 });
  19.                 $(this).find("name").each(function(){
  20.                     var name = $(this).text();
  21.                     console.log(name);
  22.                     user=user+" Name: "+name;
  23.                 });
  24.                 $(this).find("age").each(function(){
  25.                     var age = $(this).text();
  26.                     console.log(age);
  27.                     user=user+" Age: "+age;
  28.                 });
  29.             });
  30.             alert(user);
  31.         }
  32.     });
  33.    return true;
  34.  })
  35.  
  36.  $("#deleteForm").on("submit", function(){
  37.     $.ajax({
  38.         url: 'rest/userInfo',
  39.         type: 'DELETE',
  40.         dataType: "xml",
  41.         data:$("#deleteForm").serialize(),
  42.         success: function(xml) {
  43.             console.log(xml);
  44.             $(xml).find('User').each(function(){
  45.                 $(this).find("id").each(function(){
  46.                     var id = $(this).text();
  47.                     console.log(id);
  48.                     alert("Deleted the user with id "+id);
  49.                 });
  50.             });
  51.            
  52.         }
  53.     });
  54.    return true;
  55.  })
  56. });
$(document).ready(function () {

$("#updateForm").on("submit", function(){
	
	$.ajax({
	    url: 'rest/userInfo',
	    type: 'PUT',
	    dataType: "xml",
	    data:$("#updateForm").serialize(),
	    success: function(xml) {
	    	console.log(xml);
	    	var user="";
	    	$(xml).find('User').each(function(){
                $(this).find("id").each(function(){
                    var id = $(this).text();
                    console.log(id);
                    user=user+"ID: "+id;
                });
                $(this).find("name").each(function(){
                    var name = $(this).text();
                    console.log(name);
                    user=user+" Name: "+name;
                });
                $(this).find("age").each(function(){
                    var age = $(this).text();
                    console.log(age);
                    user=user+" Age: "+age;
                });
            });
	    	alert(user);
	    }
	});
   return true;
 })
 
 $("#deleteForm").on("submit", function(){
	$.ajax({
	    url: 'rest/userInfo',
	    type: 'DELETE',
	    dataType: "xml",
	    data:$("#deleteForm").serialize(),
	    success: function(xml) {
	    	console.log(xml);
	    	$(xml).find('User').each(function(){
                $(this).find("id").each(function(){
                    var id = $(this).text();
                    console.log(id);
                    alert("Deleted the user with id "+id);
                });
            });
	    	
	    }
	});
   return true;
 })
});

In this file, we are making PUT and Delete calls on respective form submission and showing the response using console log and alert.

Step 9

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.FormParam;
  8. import javax.ws.rs.GET;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.PUT;
  11. import javax.ws.rs.Path;
  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.TEXT_XML)
  25.     @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  26.     public User createUser(@FormParam("id") String id,@FormParam("name") String
  27.                                                           name,@FormParam("age") int age)      
  28.         {
  29.         User user = new User();
  30.         user.setId(id);
  31.         user.setName(name);
  32.         user.setAge(age);
  33.         User userResponse = userService.createUser(user);
  34.         return userResponse;
  35.     }
  36.  
  37.     // CRUD -- READ operation
  38.     @GET
  39.     @Produces(MediaType.APPLICATION_XML)
  40.     public List<User> getAllUsers() {
  41.         List<User> userList = userService.getAllUsers();
  42.         return userList;
  43.     }
  44.  
  45.  
  46.     // CRUD -- UPDATE operation
  47.     @PUT
  48.     @Produces(MediaType.TEXT_XML)
  49.     @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  50.     public User updateUser(@FormParam("id") String id,@FormParam("name") String
  51.                                                          name,@FormParam("age") int age)
  52.        {
  53.         User user = userService.getUserForId(id);
  54.         user.setName(name);
  55.         user.setAge(age);
  56.         User userResponse = userService.updateUser(user);
  57.         return userResponse;
  58.     }
  59.  
  60.     // CRUD -- DELETE operation
  61.     @DELETE
  62.     @Produces(MediaType.TEXT_XML)
  63.     @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  64.     public User deleteeUser(@FormParam("id") String id) {
  65.         User userResponse = userService.deleteUser(id);
  66.         return userResponse;
  67.     }
  68. }
package com.kb.rest.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
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.TEXT_XML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public User createUser(@FormParam("id") String id,@FormParam("name") String 
                                                          name,@FormParam("age") int age)      
        {
		User user = new User();
		user.setId(id);
		user.setName(name);
		user.setAge(age);
		User userResponse = userService.createUser(user);
		return userResponse;
	}

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


	// CRUD -- UPDATE operation
	@PUT
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public User updateUser(@FormParam("id") String id,@FormParam("name") String 
                                                         name,@FormParam("age") int age)
       {
		User user = userService.getUserForId(id);
		user.setName(name);
		user.setAge(age);
		User userResponse = userService.updateUser(user);
		return userResponse;
	}

	// CRUD -- DELETE operation
	@DELETE
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public User deleteeUser(@FormParam("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.

@Produces(MediaType.APPLICATION_XML)


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


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”})

Note:

We should Use application/xml for the xml to be processed by programs and we should use text/xml if we are using xml for human reading purposes.

Step 10

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 11

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.         User existingUser= usersMap.get(user.getId());
  46.         if (existingUser != null) {
  47.             existingUser.setName(user.getName());
  48.             existingUser.setAge(user.getAge());
  49.         } else {
  50.             usersMap.put(user.getId(), user);
  51.         }
  52.         return usersMap.get(user.getId());
  53.     }
  54.  
  55.     public User deleteUser(String id) {
  56.         User userResponse = usersMap.remove(id);
  57.         return userResponse;
  58.     }
  59.    }
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) {
		User existingUser= usersMap.get(user.getId());
		if (existingUser != null) {
			existingUser.setName(user.getName());
			existingUser.setAge(user.getAge());
		} 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 12

Build and deploy the project

Step 13

Let’s see the output of all CRUD operations

Access below url
http://localhost:8080/CRUDWithRestAndJSP/

CRUDWithRestAndJSP_homepage


POST

Click on create user link

CRUDWithRestAndJSP_create_Homepageinput

Fill the details and submit

We can see that data is created and we can see the same in the output

CRUDWithRestAndJSP_create_output

GET

Click on “Get User Details” link

CRUDWithRestAndJSP_read_output

PUT


Click on Update user link

Fill the details and submit

CRUDWithRestAndJSP_update_input

We can see that data is updated and we can see the same in the output.

CRUDWithRestAndJSP_update_output

DELETE

Click on Delete user link

Fill the details and submit
CRUDWithRestAndJSP_delete_input

We can see that data is deleted and we can see the same in the output

CRUDWithRestAndJSP_delete_output

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