馃殌 Integrando Thymeleaf en un Servlet Java
Hoy estuve trabajando en un servlet que utiliza Thymeleaf como motor de plantillas para manejar vistas din谩micas dentro de una aplicaci贸n Java tradicional (sin Spring Boot).
Thymeleaf puede integrarse perfectamente en un proyecto basado en Servlets si se inicializa adecuadamente el TemplateEngine.
Esto permite mantener una separaci贸n clara entre l贸gica y presentaci贸n, con vistas HTML procesadas din谩micamente desde el servidor.
package com.egga.appventas.caja;
import com.egga.appventas.include.ThymeleafConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
public class AdminCaja extends HttpServlet{
private TemplateEngine templateEngine;
@Override
public void init() {
// Inicializaci贸n del TemplateEngine usando ThymeleafConfig
ThymeleafConfig thymeleafConfig = new ThymeleafConfig();
templateEngine = thymeleafConfig.createTemplateEngine();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{ Context context = new Context();
int empresaid = (int) request.getSession().getAttribute("empresaid");
CajaService cajaService = new CajaService();
ArrayList<Caja> arraycaja = cajaService.listCaja(empresaid);
context.setVariable("arraycaja",arraycaja);
String contenido = templateEngine.process("/caja/admincaja", context);
response.setContentType("text/html");
response.getWriter().write(contenido);
}catch (IOException ex){
Context context = new Context();
context.setVariable("mensaje", ex.getMessage());
String contenido = templateEngine.process("/error/error", context);
response.setContentType("text/html");
response.getWriter().write(contenido);
}
}
}
Comentarios
Publicar un comentario