In this tutorial, we are creating a web application with two views :
- List all employees view – It display all the employees from database in a tabular format in UI. Additionally, there are links to update or delete any employee. This screen also has a separate option which can navigate to create employee screen.
- Create/update employee view – This screen is used to add a new employee or edit the details of a existing .
There are two main components in this example to focus – MVC controller and UI views.
2. Spring MVC Controller
The controller class has URL mappings and it’s handler methods. There are handler methods are all CRUD operations including POST operation to handle form submission to create/update an employee.
Notice how given handler methods are binding model data to view; and they return view names in string format which gets resolved by view resolver in HTML files.
getAllEmployees()– It returns list of all employees and is mapped to path “/”. It’s default view of the application.
editEmployeeById()– It is used to either add new or edit an existing employee. It uses the same HTML view for both operations. If there is an employee Id in context, then that employee is edited – else a new employee is created.
deleteEmployeeById()– A simple URL request to delete an employee by it’s Id.
createOrUpdateEmployee()– This method handle the HTTP POST requests which are used to either create a new employee or update an employee. Create or update operation depends on presence of employee id in model.
3. Thymeleaf templates
As stated before we are using two views in this example.
4. Entity and repository
We have bound the
EmployeeEntity class as model to UI.
To persist data in database, we are using H2 (In-Memory) Database and using Spring data’s CrudRepository interface. It provides out of the box in-built method for simple CRUD operations.
Note that repository is initialized with two SQL files which create the database tables and populate default data to it.
5. Service class
Another important class to see is
EmployeeService class through which controller interacts with repository. It contains additional business logic to perform.
6. Add Spring boot and Thymeleaf maven dependencies
In spring boot projects, we only need to add spring-boot-starter-thymeleaf dependency and project itself auto-configures thymeleaf with default configuration. It read the HTML templates from /src/main/resources/templates folder.
7. spring boot thymeleaf crud tutorial demo
Start this application as Spring boot application which starts the web application in the embedded tomcat server.
Hit the URL :
Verify that screen is rendered with two default employee details from
Play with application. Create few new employees, edit existing employees. Delete some employees.