Cover Image for Spring Boot Thymeleaf View
77 views

Spring Boot Thymeleaf View

Spring Boot with Thymeleaf is a popular combination for building web applications that require server-side rendering of HTML templates. Thymeleaf is a templating engine that integrates seamlessly with Spring Boot to render dynamic web pages. Here’s a step-by-step guide on how to create a Spring Boot application with Thymeleaf views:

Step 1: Create a Spring Boot Project:

You can create a Spring Boot project using Spring Initializr or your preferred development environment. Ensure that you select the “Thymeleaf” dependency from the available options.

Step 2: Configure Application Properties:

In your application.properties or application.yml file, configure properties related to Thymeleaf, such as template resolution and caching.

For example, in application.properties:

# Thymeleaf properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

These properties specify that Thymeleaf templates are located in the templates directory and have the .html extension. We also disable template caching for development convenience.

Step 3: Create Thymeleaf Templates:

In the src/main/resources/templates directory, create Thymeleaf HTML templates. Thymeleaf templates allow you to mix HTML with Thymeleaf expressions for dynamic content.

For example, create a hello.html template:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'"></h1>
</body>
</html>

In this template, ${name} is a Thymeleaf expression that will be replaced with the value of the name variable when rendering.

Step 4: Create a Controller:

Create a Spring MVC controller to handle requests and define which template to render.

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "Spring Boot");
        return "hello";
    }
}

In this controller, the hello method sets the name attribute in the model, which is then used in the Thymeleaf template.

Step 5: Run the Application:

Run your Spring Boot application. By default, it should start an embedded web server (e.g., Tomcat) and serve your Thymeleaf templates.

Step 6: Access the Web Page:

Open a web browser and navigate to http://localhost:8080/hello (or the appropriate URL for your application). You should see the “Hello, Spring Boot!” message rendered by Thymeleaf.

This setup demonstrates a basic Spring Boot application with Thymeleaf views. You can further enhance it by adding more templates, integrating with databases, using Thymeleaf layouts, and implementing more complex logic in your controllers and templates as needed for your web application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS