1. Introducción
Thymeleaf es un motor de plantillas Java para procesar y crear HTML, XML, JavaScript, CSS y texto.
En este artículo, discutiremos cómo usar Thymeleaf con Spring junto con algunos casos de uso básicos en la capa de vista de una aplicación Spring MVC.
La biblioteca es extremadamente extensible y su capacidad natural de creación de plantillas garantiza que las plantillas se puedan crear prototipos sin un back-end, lo que hace que el desarrollo sea muy rápido en comparación con otros motores de plantillas populares como JSP.
2. Integración de Thymeleaf con Spring
En primer lugar, veamos las configuraciones necesarias para integrarse con Spring. Se requiere la biblioteca thymeleaf-spring para la integración.
Agregue las siguientes dependencias a su archivo Maven POM:
org.thymeleaf thymeleaf 3.0.11.RELEASE org.thymeleaf thymeleaf-spring5 3.0.11.RELEASE
Tenga en cuenta que, para un proyecto de Spring 4, se debe usar la biblioteca thymeleaf-spring4 en lugar de thymeleaf-spring5 .
La clase SpringTemplateEngine realiza todos los pasos de configuración. Puede configurar esta clase como un bean en el archivo de configuración de Java:
@Bean @Description("Thymeleaf Template Resolver") public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); return templateResolver; } @Bean @Description("Thymeleaf Template Engine") public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setTemplateEngineMessageSource(messageSource()); return templateEngine; }
El prefijo y el sufijo de las propiedades del bean templateResolver indican la ubicación de las páginas de vista dentro del directorio de la aplicación web y su extensión de nombre de archivo, respectivamente.
La interfaz ViewResolver en Spring MVC asigna los nombres de vista devueltos por un controlador a los objetos de vista reales. ThymeleafViewResolver implementa la interfaz ViewResolver y se usa para determinar qué vistas de Thymeleaf representar, dado un nombre de vista.
El paso final en la integración es agregar ThymeleafViewResolver como un bean:
@Bean @Description("Thymeleaf View Resolver") public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); return viewResolver; }
3. Thymeleaf en Spring Boot
Spring Boot proporciona configuración automática para Thymeleaf agregando la dependencia spring-boot-starter-thymeleaf :
org.springframework.boot spring-boot-starter-thymeleaf 2.3.3.RELEASE
No es necesaria una configuración explícita. De forma predeterminada, los archivos HTML deben colocarse en la ubicación de recursos / plantillas .
4. Visualización de valores del origen del mensaje (archivos de propiedades)
El atributo de etiqueta th: text = ”# {key}” se puede utilizar para mostrar valores de archivos de propiedades. Para que esto funcione, el archivo de propiedades debe configurarse como bean messageSource :
@Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; }
Aquí está el código HTML de Thymeleaf para mostrar el valor asociado con la clave welcome.message :
5. Visualización de atributos del modelo
5.1. Atributos simples
El atributo de etiqueta th: text = ”$ {attributename}” se puede utilizar para mostrar el valor de los atributos del modelo. Agreguemos un atributo de modelo con el nombre serverTime en la clase del controlador:
model.addAttribute("serverTime", dateFormat.format(new Date()));
El código HTML para mostrar el valor del atributo serverTime :
Current time is
5.2. Atributos de colección
Si el atributo del modelo es una colección de objetos, el atributo th: cada etiqueta se puede usar para iterar sobre él. Definamos una clase modelo de estudiante con dos campos, id y nombre :
public class Student implements Serializable { private Integer id; private String name; // standard getters and setters }
Ahora agregaremos una lista de estudiantes como atributo de modelo en la clase de controlador:
List students = new ArrayList(); // logic to build student data model.addAttribute("students", students);
Finalmente, podemos usar el código de plantilla de Thymeleaf para iterar sobre la lista de estudiantes y mostrar todos los valores de campo:
6. Evaluación condicional
6.1. si y a menos que
El atributo th: if = ”$ {condition}” se utiliza para mostrar una sección de la vista si se cumple la condición. El atributo th: less = ”$ {condition}” se utiliza para mostrar una sección de la vista si no se cumple la condición.
Agregue un campo de género al modelo de estudiante :
public class Student implements Serializable { private Integer id; private String name; private Character gender; // standard getters and setters }
Suponga que este campo tiene dos valores posibles (M o F) para indicar el sexo del estudiante. Si deseamos mostrar las palabras "Masculino" o "Femenino" en lugar de un solo carácter, podríamos lograrlo usando el siguiente código de Thymeleaf:
6.2. interruptor y caso
Los atributos th: switch y th: case se utilizan para mostrar contenido de forma condicional utilizando la estructura de instrucción switch.
El código anterior podría reescribirse usando los atributos th: switch y th: case :
7. Manejo de la entrada del usuario
Form input can be handled using the th:action=”@{url}” and th:object=”${object}” attributes. The th:action is used to provide the form action URL and th:object is used to specify an object to which the submitted form data will be bound. Individual fields are mapped using the th:field=”*{name}” attribute, where the name is the matching property of the object.
For the Student class, we can create an input form:
In the above code, /saveStudent is the form action URL and a student is the object that holds the form data submitted.
The StudentController class handles the form submission:
@Controller public class StudentController { @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) public String saveStudent(@ModelAttribute Student student, BindingResult errors, Model model) { // logic to process input data } }
In the code above, the @RequestMapping annotation maps the controller method with URL provided in the form. The annotated method saveStudent() performs the required processing for the submitted form. The @ModelAttribute annotation binds the form fields to the student object.
8. Displaying Validation Errors
The #fields.hasErrors() function can be used to check if a field has any validation errors. The #fields.errors() function can be used to display errors for a particular field. The field name is the input parameter for both these functions.
HTML code to iterate and display the errors for each of the fields in the form:
Instead of field name the above functions accept the wild card character * or the constant all to indicate all fields. The th:each attribute is used to iterate the multiple errors that may be present for each of the fields.
The previous HTML code re-written using the wildcard *:
or using the constant all:
Similarly, global errors in Spring can be displayed using the global constant.
The HTML code to display global errors:
The th:errors attribute can also be used to display error messages. The previous code to display errors in the form can be re-written using th:errors attribute:
9. Using Conversions
The double bracket syntax {{}} is used to format data for display. This makes use of the formatters configured for that type of field in the conversionService bean of the context file.
The name field in the Student class is formatted:
The above code uses the NameFormatter class, configured by overriding the addFormatters() method from the WebMvcConfigurer interface. For this purpose, our @Configuration class overrides the WebMvcConfigurerAdapter class:
@Configuration public class WebMVCConfig extends WebMvcConfigurerAdapter { // ... @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
The NameFormatter class implements the Spring Formatter interface.
La utilidad #conversions también se puede utilizar para convertir objetos para su visualización. La sintaxis de la función de utilidad es # converssions.convert (Object, Class) donde Object se convierte al tipo Class .
Para mostrar el campo de porcentaje del objeto del estudiante sin la parte fraccionaria:
10. Conclusión
En este tutorial, hemos visto cómo integrar y usar Thymeleaf en una aplicación Spring MVC.
También hemos visto ejemplos de cómo mostrar campos, aceptar entradas, mostrar errores de validación y convertir datos para su visualización. Una versión funcional del código que se muestra en este artículo está disponible en un repositorio de GitHub.