¿Qué es Thymeleaf?
Thymeleaf es un motor de plantillas para Java que permite generar vistas HTML dinámicas del lado del servidor. Se integra perfectamente con Spring Boot y permite escribir HTML “natural”, es decir, que puede ser visualizado correctamente en navegadores incluso antes de ser procesado por el servidor.
1. Instalación en Spring Boot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Las plantillas se colocan en src/main/resources/templates
.
2. Sintaxis básica
- Mostrar variables:
<p th:text="${nombre}">Nombre por defecto</p>
- Condicionales:
<p th:if="${usuario != null}">Bienvenido</p>
- Iteraciones:
<li th:each="item : ${lista}" th:text="${item}"></li>
- Enlaces:
<a th:href="@{/login}">Iniciar sesión</a>
3. Controlador en Spring Boot
@Controller
public class HomeController {
@GetMapping("/home")
public String home(Model model) {
model.addAttribute("nombre", "Moleculax");
return "home";
}
}
4. Plantilla HTML de ejemplo
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Inicio</title></head>
<body>
<h1 th:text="'Hola, ' + ${nombre}">Hola, visitante</h1>
</body>
</html>
5. Formularios con validación
Formulario:
<form th:action="@{/registro}" th:object="${usuario}" method="post">
<input type="text" th:field="*{nombre}" />
<input type="email" th:field="*{email}" />
<button type="submit">Enviar</button>
</form>
Controlador:
@PostMapping("/registro")
public String registrar(@Valid @ModelAttribute Usuario usuario, BindingResult result) {
if (result.hasErrors()) {
return "formulario";
}
return "exito";
}
6. Seguridad con Spring Security
Dependencia:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
Ejemplo:
<div sec:authorize="hasRole('ADMIN')">Contenido solo para admins</div>
<span sec:authentication="name"></span>
7. Internacionalización
Archivo messages.properties
:
saludo=Hola, {0}
Uso en plantilla:
<p th:text="#{saludo(${nombre})}">Hola</p>