Hey guys in this post, we will discuss submitting the form data to the database in Spring boot and Thymeleaf with full coding example.
Table of Contents
Overview
- th:eachis a thymeleaf special attribute, used to iteration over collections
- th:textattribute evaluates the value expression and sets the value to the tag
- th:hrefattribute in the- <a>tag used to construct a URLs using link expression- @{...}, basically it reference to a URI.
- th:actionattribute in the- <form>tag reference to a URI using link expression- @{...}
- th:objectattribute in the- <form>tag reference to the model object which we added in the controller
- th:fieldattribute in the- <input>tag reference to the fields in the model object, we will reference to the fields using the expression- *{...}
Complete Example
We will create this example step by step, follow this tutorial till the end
Read More:
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
- Check the Spring Boot JdbcTemplate Tutorials
Create spring boot project
There are many different ways to create a spring boot application, you can follow the below articles to create one –
>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA
Add maven dependencies
Open pom.xml and add the following dependencies –
<?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.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springbootthymeleaf</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootThymeleaf</name>
	<description>Spring boot thymeleaf web app for Employee Management</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-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</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-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>
spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-thymeleaf dependency for using the thymeleaf template engine
lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString(). mysql-connector-java dependency is to store the data into the database.
Configure the datasource
Open application.properties file and add the following contents
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=scbushan05
spring.jpa.hibernate.ddl-auto=update
Create an Entity
Create Employee.java class inside in.bushansirgur.springbootthymeleaf.entity package and add the following content
package in.bushansirgur.springbootthymeleaf.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name="tbl_employees")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String email;
	
	private String department;
}
Create a Repository
Create EmployeeRepository.java interface inside in.bushansirgur.springbootthymeleaf.dao package and add the following content
package in.bushansirgur.springbootthymeleaf.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import in.bushansirgur.springbootthymeleaf.entity.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
Create a Controller
Create EmployeeController.java class inside in.bushansirgur.springbootthymeleaf.controller package and add the following content
package in.bushansirgur.springbootthymeleaf.controller;
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.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import in.bushansirgur.springbootthymeleaf.dao.EmployeeRepository;
import in.bushansirgur.springbootthymeleaf.entity.Employee;
@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeRepository eRepo;
	
	@GetMapping({"/list", "/"})
	public ModelAndView getAllEmployees() {
		ModelAndView mav = new ModelAndView("list-employees");
		mav.addObject("employees", eRepo.findAll());
		return mav;
	}
	
	@GetMapping("/addEmployeeForm")
	public ModelAndView addEmployeeForm() {
		ModelAndView mav = new ModelAndView("add-employee-form");
		Employee newEmployee = new Employee();
		mav.addObject("employee", newEmployee);
		return mav;
	}
	
	@PostMapping("/saveEmployee")
	public String saveEmployee(@ModelAttribute Employee employee) {
		eRepo.save(employee);
		return "redirect:/list";
	}
}
We are adding the new Employee() object to the ModeAndView so that we can access it inside the Thymeleaf form.
Create view template
Create list-employees.html page inside the templates folder and add the following content
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	
	<head>
		<title>List Employees</title>
		
		<link rel="stylesheet" 
			href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" 
			integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" 
			crossorigin="anonymous" />
	</head>
	
	<body>
		
		<div class="container">
		
			<h3>List Employees</h3>
			
			<hr/>
			<a th:href="@{/addEmployeeForm}" class="btn btn-primary">Add Employee</a>
			<br/><br/>
			<table class="table table-bordered table-striped">
			
				<thead>
					<tr>
						<th>Name</th>
						<th>Email</th>
						<th>Department</th>
					</tr>
				</thead>
				<tbody>
					<tr th:each="employee: ${employees}">
						<td th:text="${employee.name}" />
						<td th:text="${employee.email}" />
						<td th:text="${employee.department}" />
					</tr>
				</tbody>
				
			</table>
		</div>
		
		
	</body>
	
</html>
We are iterating the list employees using thymeleaf attribute th:each, each time loop runs thymeleaf creates temporary variable employee and we are printing the employee fields using thymeleaf attribute th:text
Create add-emplooyee-form.html inside templates folder and add the following content
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<title>Add Employee</title>
		
		<link rel="stylesheet" 
			href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" 
			integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" 
			crossorigin="anonymous" />
	</head>
	<body>
		
		<div class="container">
		
			<h3>Add New Employee</h3>
			<hr/>
			
			<form th:action="@{/saveEmployee}" th:object="${employee}" method="POST">
				
				<input type="text" th:field="*{name}" class="form-control col-4 mb-4" placeholder="Enter Name" />
				
				<input type="text" th:field="*{email}" class="form-control col-4 mb-4" placeholder="Enter email" />
				
				<input type="text" th:field="*{department}" class="form-control col-4 mb-4" placeholder="Enter department" />
				
				<button type="submit" class="btn btn-primary col-2">Save</button>
				
			</form>
			<hr/>
			<a th:href="@{/list}">Back to list</a>
		</div>
		
	</body>
</html>
We are accessing the employee object using th:object attribute and we are accessing the employee fields using th:field attribute
Run the app
Run the application using the below maven command –
mvn spring-boot:runOpen the Browser and enter the following URL –
- localhost:8080/

—

—

—
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.

Thanks this is a good starting point but missing some logic. You need a setter method for your employe in the controller. Something like this:
@ModelAttribute(“employee”)
public MetadataExport newEmployee() {
return new Employee();
}