Last updated on February 29th, 2024
In this topic, we will perform CRUD operation in the Spring Boot web application using JSP for UI design. We will create step-by-step an example of a web application in Spring Boot with Spring MVC, Spring Data JPA, Lombok and an H2 database.
Table of content:
1. Keep eclipse IDE ready(STS integrated)
2. Create a Spring Boot Starter Project
3. Maven Dependency
4. Define configuration in the application.properties file
5. Create an Entity class
6. JSP
7. Create a Repository
8. Create a Service
9. Create a Controller
10. Run the app
11. Conclusion
1. Keep eclipse IDE ready(STS Integrated)
Refer to this article How to Create Spring Project in IDE to create Spring Boot Project in Eclipse IDE.
2. Create a Spring Boot Starter Project
Add the following dependencies:
• Spring Web
• Spring Data JPA
• H2 Database
• Lombok
3. Maven Dependency
Add these dependencies in the pom.xml of the app.
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
→ We need tomcat-embed-jasper to compile JSP files.
→ JavaServer Pages Standard Tag Library(JSTL) is a collection of expressions we can use to process data in JSP files.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.springjava.poc</groupId>
<artifactId>Spring_Boot_CRUD_With_JSP</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring_Boot_CRUD_With_JSP</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
4. Define configuration in the application.properties file
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update
spring.h2.console.enabled=true
# MVC view prefix
spring.mvc.view.prefix=/WEB-INF/view/
# MVC view suffix
spring.mvc.view.suffix=.jsp
5. Create an Entity class
Student.java:
package com.springjava.poc.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String rollNo;
private String emailId;
}
6. JSP
index.jsp:
<!DOCTYPE html><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>All Students</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet"href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>
<body>
<div class="container my-2">
<div class="card">
<div class="card-body">
<div class="container my-5">
<p class="my-5">
<a href="/Spring_Boot_CRUD_With_JSP/add-student" class="btn btn-primary">
<i class="fas fa-user-plus ml-2">Add Student </i>
</a>
</p>
<div class="col-md-10">
<c:if test="${students.size()==0}">
<h2>No record found !!</h2>
</c:if>
<c:if test="${students.size() gt 0 }">
<div>
<table class="table table-striped table-responsive-md">
<thead>
<tr>
<th>Name</th>
<th>RollNo.</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.name}</td>
<td>${student.rollNo}</td>
<td>${student.emailId}</td>
<td>
<a href="/Spring_Boot_CRUD_With_JSP/student-update/${student.id}" class="btn btn-primary">
<i class="fas fa-user-edit ml-2"></i></a>
</td>
<td>
<a href="/Spring_Boot_CRUD_With_JSP/student-delete/${student.id}" class="btn btn-primary">
<i class="fas fa-user-times ml-2"></i>
</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</c:if>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
add_student.jsp:
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Add Student</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>
<body>
<div class="container my-5">
<h3>Add Student</h3>
<div class="card">
<div class="card-body">
<div class="col-md-10">
<form:form action="/Spring_Boot_CRUD_With_JSP/save-student"
method="post" modelAttribute="command">
<form:hidden path="id" />
<div class="row">
<div class="form-group col-md-8">
<label for="name" class="col-form-label">Name</label>
<form:input type="text" class="form-control" id="name"
path="name" placeholder="Enter Name" />
</div>
<div class="form-group col-md-8">
<label for="name" class="col-form-label">Roll No.</label>
<form:input type="text" class="form-control" id="rollNo"
path="rollNo" placeholder="Enter Roll No." />
</div>
<div class="form-group col-md-8">
<label for="email" class="col-form-label">Email</label>
<form:input type="text" class="form-control" id="email"
path="emailId" placeholder="Email Id" />
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-primary" value=" Submit ">
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</body>
</html>
→ In this form tags are provided by the Spring MVC form tag library. This gives the tag access to the command object.
7. Create a Repository
StudentRepository.java:
package com.springjava.poc.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springjava.poc.entity.Student;
public interface StudentRepository extends JpaRepository<Student, Integer> {
}
8. Create a Service
StudentService.java:
package com.springjava.poc.service;
import java.util.List;
import com.springjava.poc.entity.Student;
public interface StudentService {
void save(Student student);
List<Student> getAll();
Student getById(Integer id);
void delete(Student student);
}
StudentServiceImpl.java:
package com.springjava.poc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springjava.poc.entity.Student;
import com.springjava.poc.repository.StudentRepository;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
StudentRepository studentRepository;
@Override
public void save(Student student) {
if (student.getId() == null) {
studentRepository.save(student);
} else {
Student staffUpdate = studentRepository.findById(student.getId()).get();
staffUpdate.setName(student.getName());
staffUpdate.setRollNo(student.getRollNo());
staffUpdate.setEmailId(student.getEmailId());
studentRepository.save(staffUpdate);
}
}
@Override
public List<Student> getAll() {
return studentRepository.findAll();
}
@Override
public Student getById(Integer id) {
return studentRepository.findById(id).get();
}
@Override
public void delete(Student student) {
studentRepository.delete(student);
}
}
9. Create a Controller
StudentController.java:
package com.springjava.poc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springjava.poc.entity.Student;
import com.springjava.poc.service.StudentService;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping("/")
public ModelAndView getAllStudents() {
ModelAndView mav = new ModelAndView("index");
List<Student> studentList = studentService.getAll();
mav.addObject("students", studentList);
return mav;
}
@GetMapping("/add-student")
public ModelAndView addStudent() {
ModelAndView mav = new ModelAndView("add_student");
mav.addObject("command", new Student());
return mav;
}
@PostMapping("/save-student")
public String saveStaff(@ModelAttribute Student student) {
studentService.save(student);
return "redirect:/";
}
@GetMapping("/student-update/{id}")
public ModelAndView getStaff(@PathVariable("id") Integer id) {
ModelAndView mav = new ModelAndView("add_student");
Student student = studentService.getById(id);
mav.addObject("command", student);
return mav;
}
@GetMapping("/student-delete/{id}")
public String deleteStaff(@PathVariable("id") Integer id) {
Student deleteStaff = studentService.getById(id);
studentService.delete(deleteStaff);
return "redirect:/";
}
}
→ ModelAndView is a class which is a holder for both Model and View in the Spring MVC framework. This class holds both to make it possible for a controller to return both model and view in a single return value. The view can take the form of a String view name which will need to be resolved by a ViewResolver object and alternatively a View object can be specified directly. The model is a Map which allows the use of multiple objects keyed by name.
→ @ModelAttribute annotation can also expose reference data to a web view by annotating accessor methods in a controller class.
10. Run the app
Right-click on the app then click on Run As and select Run on Server.
11. Conclusion
In this topic, we implemented CRUD operation in the Spring Boot web application with the JSP view pages.
nice