Spring boot thymeleaf jQuery Datatable




Hey guys in this post, we will discuss adding jQuery datatable to the Spring boot and Thymeleaf web application with full coding example

Complete Example


We will create this example step by step, follow this tutorial till the end

Read More:

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.bind.annotation.RequestParam;
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";
	}
	
	@GetMapping("/showUpdateForm")
	public ModelAndView showUpdateForm(@RequestParam Long employeeId) {
		ModelAndView mav = new ModelAndView("add-employee-form");
		Employee employee = eRepo.findById(employeeId).get();
		mav.addObject("employee", employee);
		return mav;
	}
	
	@GetMapping("/deleteEmployee")
	public String deleteEmployee(@RequestParam Long employeeId) {
		eRepo.deleteById(employeeId);
		return "redirect:/list";
	}
}

We are calling the repository method deleteById() and redirecting to the /list URI which will update the list.

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" 
			type="text/css" 
			href="https://cdn.datatables.net/v/bs4/dt-1.10.25/datatables.min.css" />
		<link rel="stylesheet" 
			href="https://cdn.jsdelivr.net/npm/[email protected]/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" id="employeeTable">
			
				<thead>
					<tr>
						<th>Name</th>
						<th>Email</th>
						<th>Department</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
					<tr th:each="employee: ${employees}">
						<td th:text="${employee.name}" />
						<td th:text="${employee.email}" />
						<td th:text="${employee.department}" />
						<td>
							<a th:href="@{/showUpdateForm(employeeId=${employee.id})}" class="btn btn-info">Update</a>
							
							<a th:href="@{/deleteEmployee(employeeId=${employee.id})}" class="btn btn-danger ml-2">Delete</a>
						</td>
					</tr>
				</tbody>
				
			</table>
		</div>
		
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
		<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/dt-1.10.25/datatables.min.js"></script>
		<script>
			$(document).ready(function() {
				$("#employeeTable").DataTable({
						'aoColumnDefs': [{
        				'bSortable': false,
        				'aTargets': [-1] /* 1st one, start by the right */
    				}]
				});
			})
		</script>
	</body>
	
</html>
  • Inside the <head> section, we will reference to the jQuery datatable style library using CDN.
  • Just before closing the </body> tag we will reference to the jQuery library and jQuery datatable library using CDN.
  • jQuery datatable is dependent on jQuery core library so first we reference to the jQuery core library.
  • Next we will target the <table> using id selector and call the DataTable() to add the DataTable $("#employeeTable").DataTable();
  • Next we are disabling the sorting option for last column by setting bSortable option to false and specifying the last column index to -1 using aTargets option

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/[email protected]/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>
				<input type="hidden" th:field="*{id}" />
				
			</form>
			<hr/>
			<a th:href="@{/list}">Back to list</a>
		</div>
		
	</body>
</html>

We are creating hidden <input> tag to track the employee id. 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:run

Open the Browser and enter the following URL –

  • localhost:8080/

Screenshot-2021-08-22-at-12-10-18-PM

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.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply