Advertisement
andersonalmada

Untitled

Jul 1st, 2022
551
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None
  1. package config;
  2.  
  3. import org.thymeleaf.ITemplateEngine;
  4. import org.thymeleaf.TemplateEngine;
  5. import org.thymeleaf.templatemode.TemplateMode;
  6. import org.thymeleaf.templateresolver.WebApplicationTemplateResolver;
  7. import org.thymeleaf.web.IWebApplication;
  8. import org.thymeleaf.web.servlet.JakartaServletWebApplication;
  9.  
  10. import jakarta.servlet.ServletContextEvent;
  11. import jakarta.servlet.ServletContextListener;
  12. import jakarta.servlet.annotation.WebListener;
  13.  
  14. @WebListener
  15. public class ThymeleafConfig implements ServletContextListener {
  16.  
  17.     public static final String TEMPLATE_ENGINE_ATTR = "TemplateEngineInstance";
  18.  
  19.     private ITemplateEngine templateEngine;
  20.  
  21.     private JakartaServletWebApplication application;
  22.  
  23.     @Override
  24.     public void contextInitialized(ServletContextEvent sce) {
  25.         this.application = JakartaServletWebApplication.buildApplication(sce.getServletContext());
  26.         this.templateEngine = templateEngine(this.application);
  27.  
  28.         sce.getServletContext().setAttribute(TEMPLATE_ENGINE_ATTR, templateEngine);
  29.     }
  30.  
  31.     private ITemplateEngine templateEngine(IWebApplication application) {
  32.         TemplateEngine templateEngine = new TemplateEngine();
  33.  
  34.         WebApplicationTemplateResolver templateResolver = templateResolver(application);
  35.         templateEngine.setTemplateResolver(templateResolver);
  36.  
  37.         return templateEngine;
  38.     }
  39.  
  40.     private WebApplicationTemplateResolver templateResolver(IWebApplication application) {
  41.         WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application);
  42.  
  43.         templateResolver.setTemplateMode(TemplateMode.HTML);
  44.         templateResolver.setPrefix("/WEB-INF/templates/");
  45.         templateResolver.setSuffix(".html");
  46.  
  47.         return templateResolver;
  48.     }
  49.  
  50.     @Override
  51.     public void contextDestroyed(ServletContextEvent sce) {
  52.        
  53.     }
  54. }
Advertisement
RAW Paste Data Copied
Advertisement