Show List

Sample Spring MVC CRUD Application

In this sample Spring MVC application we will be implementing create read update and delete (CRUD) operations. In your IDE create a new maven project with webapp archetype. I am using IntelliJ IDE.

We will be using in memory H2 database and Spring Data JPA.

Here is the project structure and different files. You can see that the model, view and controller are at different layers of the project.
In terms of maven dependencies, we will be using spring boot starter web, h2, jpa, jstl and taglibs. Below is the pom.xml with dependencies. jstl and taglibs are used to display the data on the JSP pages.

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.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
web.xml (Front Controller)
This is the dispatcher servlet or the front controller of the application. It uses spring bean configuration file spring-servlet.xml to identify the handler controllers for different requests and view resolvers
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web basepackage.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>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 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">
<!-- Finding Controllers -->
<annotation-driven />
<context:component-scan base-package="basepackage" />
<!-- Resolving views selected for data returned by @Controllers -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>


Student.java (Model)
This is the data object used in the application.
package basepackage.model;

import javax.persistence.*;

@Entity
@Table
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String grade;

public Student() {

}

public Student(String name, String grade) {
this.name = name;
this.grade = grade;
}

public int getId() {
return id;
}

public void setId(int student_id) {
this.id = student_id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}
}
StudentRepo.java
package basepackage.dao;

import basepackage.model.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepo extends CrudRepository<Student, Integer> {}
application.properties
spring.jpa.show-sql=true
WebController.java
It handles various various CRUD requests and calls dao layer to provide the requested data. It the passes the data invoking the view to display results. 
package basepackage.controller;

import basepackage.dao.StudentRepo;
import basepackage.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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;

import java.util.List;
import java.util.Optional;

@Controller
public class WebController {

@Autowired
private StudentRepo repo;

@RequestMapping(value="/save",method = RequestMethod.POST)
public String save(@ModelAttribute("student") Student student){
repo.save(student);
return "redirect:/viewstudent";//will redirect to viewstudent request mapping
}


@RequestMapping("/viewstudent")
public String viewStudents(Model m){
List<Student> list= (List<Student>) repo.findAll();
m.addAttribute("studentlist",list);
return "viewstudentpage";
}

@RequestMapping("/addstudent")
public String addStudent(Model m){
m.addAttribute("command", new Student());
return "addstudentpage";
}

@RequestMapping("/editstudent/{id}")
public String edit(@PathVariable int id, Model m){
Optional<Student> student=repo.findById(id);
m.addAttribute("command",student);
return "editstudentpage";
}

@RequestMapping(value="/editsave",method = RequestMethod.POST)
public String editsave(@ModelAttribute("student") Student student){
repo.save(student);
return "redirect:/viewstudent";
}

@RequestMapping(value="/deletestudent/{id}",method = RequestMethod.GET)
public String delete(@PathVariable int id){

repo.deleteById(id);
return "redirect:/viewstudent";
}

@RequestMapping("/")
public String displayHomeForDefault(ModelMap model) {
model.addAttribute("message", "Welcome Home");
return "home";
}

@RequestMapping("/home")
public String displayHome(ModelMap model) {
model.addAttribute("message", "Welcome Home");
return "home";
}

}
Here are different views used by the application to display the homepage, student list, add student and edit student.

home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<a href="addstudent">Add Student</a>
<a href="viewstudent">View Student</a>
</body>
</html>
viewstudentpage.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Students List</h1>
<table border="2" width="70%" cellpadding="2">
<tr>
<th>Id</th>
<th>Name</th>
<th>Grade</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="student" items="${studentlist}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.grade}</td>
<td><a href="editstudent/${student.id}">Edit</a></td>
<td><a href="deletestudent/${student.id}">Delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<a href="addstudent">Add New Student</a>
addstudentpage.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Student</h1>
<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>Grade :</td>
<td>
<form:input path="grade" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form:form>
editstudentpage.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Student</h1>
<form:form method="POST" action="/springmvcexample/editsave">
<table >
<tr>
<td></td>
<td>
<form:hidden path="id" />
</td>
</tr>
<tr>
<td>Name : </td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>Grade :</td>
<td>
<form:input path="grade" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Edit Save" />
</td>
</tr>
</table>
</form:form>
When the application is run add/edit/delete/view students actions can be done from the UI:

home
Add Student
View/Delete Student
Edit Student
Source Code:
https://github.com/it-code-lab/springmvccrud

    Leave a Comment


  • captcha text