How to Serve Static Resources and Render Pages with Spring Boot & Thymeleaf
This guide explains how Spring Boot serves static assets from classpath directories, how to configure and access them, and how to render dynamic HTML pages using Thymeleaf—including template locations, sample code, and property customizations for seamless web development.
Spring Boot serves static resources from classpath locations /static, /public, /resources and /META-INF/resources. Place files under src/main/resources/static and access them via URLs such as http://localhost:8080/D.jpg.
For rendering HTML pages, Spring Boot supports several template engines; Thymeleaf is the recommended choice. The default template directory is src/main/resources/templates.
Thymeleaf basics
Thymeleaf is an XML/HTML5 template engine that integrates with Spring MVC, allowing server‑side processing through HTML attributes while keeping the page viewable directly in a browser.
<table>
<thead>
<tr>
<th th:text="#{{msgs.headers.name}}">Name</th>
<th th:text="#{{msgs.headers.price}}">Price</th>
</tr>
</thead>
<tbody>
<tr th:each="prod : ${allProducts}">
<td th:text="${prod.name}">Oranges</td>
<td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
</tr>
</tbody>
</table>To use Thymeleaf, add the Maven dependency spring-boot-starter-thymeleaf and create a controller that returns the view name:
@Controller
public class HelloController {
@RequestMapping("/")
public String index(ModelMap map) {
map.addAttribute("host", "http://blog.didispace.com");
return "index";
}
}The corresponding index.html template can be:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Hello</title></head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>When the application runs, accessing http://localhost:8080/ renders the page with the host value, demonstrating clean separation of data logic from HTML.
Customizing Thymeleaf properties
Properties can be overridden in application.properties as needed, for example:
spring.thymeleaf.cache=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.htmlSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
