Springboot with Thymeleaf

Thymeleaf is a template language that helps serve static files.

Add dependencies

<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>

Controller methods

Use Model class to pass data to html files

@Api(value = "home", tags = "HomeController")
@Slf4j
@Controller
public class HomeController {

    @GetMapping
    public String showHome(Model model, @RequestParam String name) {
        log.info("home");
        model.addAttribute("name", name);

        return "index";
    }

}

 

Static files

HTML files

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no">

<title>Spring Boot Thymeleaf Hello World Example</title>

<!-- CSS only -->
<link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
    integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
    crossorigin="anonymous">

<link rel="stylesheet" href="/css/style.css">


</head>

<body>

    <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="#">folaukaveinga.org</a>
    </nav>

    <main role="main" class="container">

        <div class="starter-template">
            <h1>Spring Boot Web Thymeleaf Example</h1>
            <h2>
                Hello, <span id="name" th:text="${name}"></span>
            </h2>
        </div>

    </main>
    <!-- /.container -->


    <!-- JS, Popper.js, and jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script
        src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
        integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
        crossorigin="anonymous"></script>
    <script
        src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
        integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
        crossorigin="anonymous"></script>
</body>
</html>

CSS files

resources/static/css/style.css

#name{
    color: blue;
}

Js files

resources/static/js/index.js

$(function() {

    $("#sayHiBtn").click(function() {
        alert("Hello World!");
    });

});

Source code on Github

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.