Adding CSS and JS Files to Thymeleaf Template

In this tutorial,  we show how to add custom CSS and JS files to Thymeleaf templates in Spring boot MVC applications.

We assume that you have already a Spring boot MVC application and you want to add custom CSS and JS files to your existing application.

Create Spring MVC Controller - DemoController

Within a Spring MVC controller, let's create a handler method to handle the request and return the view:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DemoController {

    @GetMapping("custom-css-js")
    public String demo(){
        return "custom-css-js";
    }
}

Create Thymeleaf Template

Within the resources/templates folder, let's create a Thymeleaf template named "custom-css-js" and add the below content to it:
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
    <link th:href="@{/css/main.css}" rel="stylesheet">
</head>
<body>
   <div class="center">
       <h2>Page Heading</h2>
       <p>Demo to add custom css and JS to Thymeleaf Template</p>
       <button type="button" th:onclick="showAlert()"> Show Alert</button>
   </div>
<script th:src="@{/js/main.js}" type="text/javascript"></script>
</body>
</html>

Create main.css File

Within the resources/static folder, create a new folder named "CSS" and within the CSS folder, let's create a main.css file with the below content in it:
h2 {
    text-transform: uppercase;
}

.center {
  margin: auto;
  width: 50%;
  border: 3px solid green;
  padding: 10px;
}

p {
    font-size: 15px;
}

Create main.js File

Within the resources/static folder, create a new folder named "js" and within the js folder, let's create a main.js file with the below content in it:
function showAlert(){
    alert("Add Custom CSS and JS to Thymeleaf Template");
}

Run Spring Boot Application

Hit this URL in the browser: http://localhost:8080/custom-css-js
Click on Alert Button to call the JavaScript function in the main.js file:

Note that in the first screenshot, the CSS is applied to the HTML elements in the Thymeleaf HTML page, and in the second screenshot the JavaScript function has called. It means that we have successfully added  CSS and JS Files to Thymeleaf Template.


Comments