4.4 Fundamentals of Static Resources and View Rendering
In software architecture, backend servers can either perform the role of drawing screens for browsers (View Rendering) or purely returning raw data payloads (REST API).
1. Static Resources
Files like HTML, CSS, JS, and Images whose contents do not dynamically change due to application logic are called static resources. Spring Boot maps files in the following locations as static resources by default.
src/main/resources/
├── static/ (Placing index.html here creates your root home page)
├── public/
├── resources/
└── META-INF/resources/
For instance, if a file exists at src/main/resources/static/css/style.css, a client browser can actively request it via http://localhost:8080/css/style.css.
2. Server-Side Rendering (SSR) and Template Engines
The paradigm where Spring controller logic fetches DB data to build a dynamic HTML payload before responding to the client browser is known as SSR (Server Side Rendering). Spring Boot officially recommends Thymeleaf.
Thymeleaf View Rendering Example
- Writing the Controller
@Controller
public class ViewController {
@GetMapping("/hello")
public String hello(Model model) {
// Send data attributes required for HTML parsing via the Model box
model.addAttribute("data", "Hello, Spring!");
// Logical view name returned -> Spring resolves to src/main/resources/templates/home.html
return "home";
}
}
- Writing the Thymeleaf HTML Template (
resources/templates/home.html)
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello View</title>
</head>
<body>
<!-- The 'data' string previously passed by the controller overwrites the target text value -->
<h1 th:text="${data}">Default Text (This text will be overwritten when the engine parses)</h1>
</body>
</html>
Unlike static resources, these dynamic screen templates must be safely insulated under src/main/resources/templates/ so they cannot be arbitrarily viewed or directly accessed by external users via URL routines.