Spring Boot Thymeleaf Ajax Example

This Spring Boot Thymeleaf Ajax Example will shows you how to create a simple web application based on Spring Boot and Thymeleaf template + jQuery.ajax. Here, we are using jQuery.ajax function to send a request to Spring REST API and return a JSON response.

Other interesting posts you may like

Let’s begin:

Project Structure
In the Spring Boot Thymeleaf Ajax Example, our project is with this structure below

Spring Boot Thymeleaf Ajax Example

Maven Dependency
In the Spring Boot Thymeleaf Ajax Example, we are using A normal Spring Boot Thymeleaf starter dependency and some webjars resources.

Create Spring Controller
We create a simple controller to display login page

Create Spring REST API
We create a REST API which accepts a submit request on the login form and return the result using ResponseEntity format.

Create some POJO

AjaxResponseBody POJO

User POJO

Form Validation
The form data will be validated by using JSR 303 validation

A service to validate a valid user
Our service will find user information from database or other resources

Spring Boot Web Application
Don’t forget to create the Spring Boot Web Application and sometimes it is call to be Spring Boot Starter

HTML form using Thymeleaf template
In our Spring Boot Thymeleaf Ajax Example, we create a simple HTML form uing the Thymeleaf template and bootstrap css.

Ajax submit function
Gets HTML form then convert form data into JSON format via JSON.stringify, and send POST request using the jQuery.ajax function

Demo Spring application
Go to the project directory and run the command line

Then the successful screen should be like this:

Now, let’s access the address http://localhost:8080/ and the login form looks like below

Spring Boot Thymeleaf Ajax Example

Submit the login form without data, the validation error should display

Spring Boot Thymeleaf Ajax Example

Enter username/password on the form

Spring Boot Thymeleaf Ajax Example

Then click submit button, the user information is displayed when the login is successful

Spring Boot Thymeleaf Ajax Example

That’s all on the Spring Boot Thymeleaf Ajax Example.

References
Spring IO – Building a RESTful Web Service
MDN – JSON.stringify()

Download complete source code, click link below

spring-boot-thymeleaf-ajax-example.zip (79 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons