In this tutorial, we show how to add a bootstrap CSS 5 to Thymeleaf templates in Spring boot MVC applications.
We assume that you have already a Spring boot MVC application and you want to add bootstrap CSS 5 to Thymeleaf templates 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("bootstrap")
public String demo(){
return "bootstrap";
}
}
Download bootstrap.min.css files
Keep the bootstrap.min.css file in the resources/static folder.
Create Thymeleaf Template
Within the resources/templates folder, let's create a Thymeleaf template named "bootstrap" 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/bootstrap.min.css}" rel="stylesheet"> </head> <body> <div class="container"> <h1 class="text-center">Page Heading</h1> <table class="table table-striped table-bordered"> <thead class="table-dark"> <tr> <th>First Name</th> <th>Last Name</th> </tr> </thead> <tbody> <tr> <td>Ramesh</td> <td>Fadatare</td> </tr> <tr> <td>Umesh</td> <td>Fadatare</td> </tr> </tbody> </table> </div> </body> </html>
Note that we have included a bootstrap CSS file:
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
Using Bootstrap 5 CDN Link
You can also use the bootstrap 5 remote CDN link to use the bootstrap in a Thymeleaf HTML file:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
>
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1 class="text-center">Page Heading</h1>
<table class="table table-striped table-bordered">
<thead class="table-dark">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ramesh</td>
<td>Fadatare</td>
</tr>
<tr>
<td>Umesh</td>
<td>Fadatare</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Bootstrap 5 CDN link:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
Run Spring Boot Application
Hit this URL in the browser: http://localhost:8080/bootstrapFree Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course