How to perform CRUD operation in Spring MVC

In this article, we will understand how to perform CRUD operations in Spring MVC. We will perform insertion, deletion, and updation.

CRUD Operations are the most important operation we have to perform while building any web-based application. CRUD acronyms to Create, Read, Update, Delete. These are the basic things that your application should support as well as a developer you should know. So, we will be creating a complete CRUD Operation example in Spring MVC.

To connect with the database, we will be using JDBCTemplate. In case you want a clear idea of what is JDBCTemplae check this article How to use JDBC with Spring

The following are the technologies and tools we will need:

  • Core java
  • Spring MVC
  • Mysql Database
  • Spring STS
  • Tomcat Apache Server

Steps to perform CRUD operation using Spring MVC

  • Create a database and table
  • Create a Maven project in Spring STS.
  • Add the dependencies.
  • Create the web.xml to configure DisptacherServlet
  • Create a Spring-servlet.xml file to configure data source, JDBC template, and Data Access layer.
  • Create a Model class
  • Create a DAO class to make a data access layer.
  • Create a Controller
  • Create views inside the WEB-INF/view/ folder.

Let us do each step one by one: Here we will perform a CRUD operation on Doctor User

Create a Database and table

The first step is to create a database named ‘doctordb’ using the MYSQL command line or Workbench.

Create database doctordb;

Now, use the database and create a table doctor

CREATE TABLE `doctor` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `specialist` varchar(45) DEFAULT NULL,
  `city` varchar(45) DEFAULT NULL,
  `country` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

Create a Project in Spring STS

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

The project structure should like the following:

Add the following dependencies into the pom.xml files

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->  
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <version>8.0.11</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-jdbc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>

Create a web.xml file

  •  Web.xml is a deployment descriptor that is used by the server to map the incoming request.
<!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>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/Spring-servlet.xml</param-value>
    </init-param>   
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>  
</web-app>

Create a Spring-servlet.xml

  • Here, we have used <context:component-scan> detects the annotation by package scanning.
  • To resolves views such as JSP, we have used InternalResourceViewResolver.
  • Initialize and configure the DataSource. Specify Database connection properties here.
  • Add the DoctorDAO.java bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">

  <!-- component scan -->
  <context:component-scan base-package="org.mvc"></context:component-scan>


  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
  </bean>

  <!-- Initialize Data Source -->
  <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"
      value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/doctordb" />
    <property name="username" value="root" />
    <property name="password" value="khan" />
  </bean>

  <bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
  </bean>

  <!-- Define DoctorDAO bean -->
  <bean id="doctordao" class="org.mvc.dao.DoctorDAO">
    <property name="jdbcTemplate" ref="jdbcTemplate"></property>
  </bean>
</beans>

Create a Model class – Doctor.java

Create a Model class Doctor.java that will contain attributes with setters and getters inside the model package.

package org.mvc.model;

public class Doctor {

  private Integer id;
  private String name;
  private String specialist;
  private String email;
  private String city;
  private String country;
  public Integer getId() {
    return id;
  }
  public void setId(Integer id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getSpecialist() {
    return specialist;
  }
  public void setSpecialist(String specialist) {
    this.specialist = specialist;
  }
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  public String getCity() {
    return city;
  }
  public void setCity(String city) {
    this.city = city;
  }
  public String getCountry() {
    return country;
  }
  public void setCountry(String country) {
    this.country = country;
  }
  public Doctor() {
    
  }
  
  
}

Create a DAO class – DoctorDAO.java

  • Create a Data access layer to interact with the database.
  • This class will have all the CRUD Operations.
  • It contains methods to ADD doctors, Edit doctors, and Delete Doctors inside dao package.
package org.mvc.dao;

import java.util.List;

import org.mvc.model.Doctor;
import org.springframework.jdbc.core.JdbcTemplate;

public class DoctorDAO {

  private JdbcTemplate jdbcTemplate;

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public int insert(Doctor doctor) {
    String sql = "insert into doctor (name,email,specialist, city,country) " + "values ('" + doctor.getName()
        + "','" + doctor.getEmail() + "','" + doctor.getSpecialist() + "','" + doctor.getCity() + "','"
        + doctor.getCountry() + "') ";
    return jdbcTemplate.update(sql);
  }

  public int update(Doctor doctor) {
    String sql = "update doctor set name = '" + doctor.getName() + "', email = '" + doctor.getEmail()
        + "', specialist = '" + doctor.getSpecialist() + "', city = '" + doctor.getCity() + "', country='"
        + doctor.getCountry() + "' where id = '"+doctor.getId()+"' ";
    return jdbcTemplate.update(sql);
  }

  public int delete(int id) {
    String sql = "delete from doctor where id = '" + id + "'";
    return jdbcTemplate.update(sql);
  }

  public Doctor getDoctorById(int id) {
    String sql = "select * from doctor where id = '" + id + "'";
    return jdbcTemplate.queryForObject(sql, new RowMapperImpl());
  }

  public List<Doctor> getListOfDoctors() {
    String sql = "select * from doctor";
    return jdbcTemplate.query(sql, new RowMapperImpl());
  }
}

Create a class RowMapperImpl inside dao package to convert the resultset from the table to an object and use it in DoctorDAO.java

package org.mvc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.mvc.model.Doctor;
import org.springframework.jdbc.core.RowMapper;

public class RowMapperImpl implements RowMapper<Doctor> {

  @Override
  public Doctor mapRow(ResultSet rs, int rowNum) throws SQLException {
    // TODO It will convert the result-set into objects
    Doctor doctor = new Doctor();
    doctor.setId(rs.getInt(1));
    doctor.setName(rs.getString(2));
    doctor.setEmail(rs.getString(3));
    doctor.setSpecialist(rs.getString(4));
    doctor.setCity(rs.getString(5));
    doctor.setCountry(rs.getString(6));
    return doctor;
  }
  

}

Create a Controller – DoctorController

  • The @Controller here defines the class as Controller in SpringMVC.
  • The @RequestMapping is used to map the URL.
package org.mvc.controller;

import java.util.List;

import org.mvc.dao.DoctorDAO;
import org.mvc.model.Doctor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class DoctorController {
  @Autowired
  private DoctorDAO dao;

  @RequestMapping(value = {"/","/index"})
  public String home(Model model) {
    List<Doctor> list = dao.getListOfDoctors();
    model.addAttribute("list", list);
    return "index";
  }
  
  @RequestMapping("/doctorform")
  public String showForm(Model model) {
    model.addAttribute("doctor", new Doctor());
    return "add_doctor";  //WEB-INF/views/add-doctor.jsp
  }
  /*
   * This method will save an doctor object into table.
   */
  @RequestMapping(value = "/add" , method = RequestMethod.POST)
  public String addDoctor(@ModelAttribute("doctor") Doctor d) {
    dao.insert(d);
    return "redirect:/index";  //WEB-INF/views/add-doctor.jsp
  }
  /*
   * This method will show the Edit Doctor Page to user
   */
  @RequestMapping(value = "editdoctorform/{id}")
  public String showEditForm(@PathVariable("id") Integer id, Model model) {
    Doctor doctor = dao.getDoctorById(id);
    model.addAttribute("doctor", doctor);
    return "update_doctor";  //WEB-INF/views/update-doctor.jsp
  }
  /*
   * This method will update doctor's information
   */
  @RequestMapping(value = "/update" , method = RequestMethod.POST)
  public String updateDoctor(@ModelAttribute("doctor") Doctor d) {
    dao.update(d);
    return "redirect:/index";  //WEB-INF/views/index.jsp
  }
  @RequestMapping(value = "deletedoctor/{id}")
  public String deleteDoctor(@PathVariable("id") Integer id, Model model) {
    dao.delete(id);
    return "redirect:/index";  //WEB-INF/views/index.jsp
  }
  
}

Create Views

  • All the views will be created in WEB-INF/view/ folder.
  • Create index. jsp to show a link to add a new doctor and list the doctors from the database.
  • Craete add_doctor.jsp to add new doctor.
  • Craete update_doctor.jsp to edit a doctor information.

index.jsp

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<title>Spring MVC</title>
</head>
<body style="background-color: #e2e2e2">
<div class="container mt-5">
<h1 align="center" style="font-weight: bold; ">Spring MVC CRUD Example + JDBCTemplate</h1>
<a href="doctorform" class="btn btn-info" style="font-weight: bold;">Add New Doctor</a>
<table class="table mt-5 table-info ">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
      <th scope="col">Specialist</th>
      <th scope="col">City</th>
      <th scope="col">Country</th>
      <th scope="col">Action
      </th>
    </tr>
  </thead>
  <tbody>
  <c:forEach var="doc" items="${list}">
    <tr>
      <th scope="row"><c:out value="${doc.id }"/></th>
      <td><c:out value="${doc.name}"/></td>
      <td><c:out value="${doc.email}"/></td>
      <td><c:out value="${doc.specialist}"/></td>
      <td><c:out value="${doc.city}"/></td>
      <td><c:out value="${doc.country}"/></td>
      <td><a href="editdoctorform/<c:out value="${doc.id}"/>" class="btn btn-warning">Edit</a>
      <a href="deletedoctor/<c:out value="${doc.id}"/>" class="btn btn-danger">Delete</a>
      </td>
      
    </tr>
    </c:forEach>
  </tbody>
</table>
</div>
  
</body>
</html>

add_doctor.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add Doctor</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>

<body style="background-color: #e2e2e2">
<div class="container mt-5">
  <div class="card " style="width: 25rem; ">
    <div class="card-body">
      <h5 class="card-title " align="center" >Add Doctor</h5>
      <f:form modelAttribute="doctor" action="add" method="post">
        <div class="form-group">
          <label for="exampleInputEmail1">Name</label>
          <f:input path="name" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Email</label>
          <f:input path="email" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Specialist</label>
          <f:input path="specialist" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">City</label>
          <f:input path="city" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Country</label>
          <f:input path="country" class="form-control" />
        </div><br>
        <div class="form-group mt-2 ">
        <center>	<input type="submit" value="Add Doctor" class="btn btn-warning"></center>
        </div>

      </f:form>

    </div>
  </div>
</div>	
</body>
</html>

update_doctor.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add Doctor</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>

<body style="background-color: #e2e2e2">
<div class="container mt-5">
  <div class="card " style="width: 25rem; ">
    <div class="card-body">
      <h5 class="card-title " align="center" >Edit Doctor</h5>
      <f:form modelAttribute="doctor" action="/SpringMVCCRUD/update" method="post">
      <f:hidden path="id"/>
        <div class="form-group">
          <label for="exampleInputEmail1">Name</label>
          <f:input path="name" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Email</label>
          <f:input path="email" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Specialist</label>
          <f:input path="specialist" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">City</label>
          <f:input path="city" class="form-control" />
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Country</label>
          <f:input path="country" class="form-control" />
        </div><br>
        <div class="form-group mt-2 ">
        <center>	<input type="submit" value="Update Doctor" class="btn btn-warning"></center>
        </div>

      </f:form>

    </div>
  </div>
</div>	
</body>
</html>

In this way, we create a CRUD Application in Spring MVC.