2.2 创建和配置模板引擎

我们的过滤器里的process(…)方法包含了如下这行:

ITemplateEngine templateEngine = this.application.getTemplateEngine();

这意味着GTVGApplication类管理着创建和配置Thymeleaf 应用里最重要的对象之一:TemplateEngine实例(ITemplateEngine接口的实现)。

我们的org.thymeleaf.TemplateEngine对象会像这样被初始化:

public class GTVGApplication {


    ...
    private final TemplateEngine templateEngine;
    ...


    public GTVGApplication(final ServletContext servletContext) {

        super();

        ServletContextTemplateResolver templateResolver = 
                new ServletContextTemplateResolver(servletContext);

        // HTML is the default mode, but we set it anyway for better understanding of code
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // This will convert "home" to "/WEB-INF/templates/home.html"
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        // Template cache TTL=1h. If not set, entries would be cached until expelled by LRU
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));

        // Cache is set to true by default. Set to false if you want templates to
        // be automatically updated when modified.
        templateResolver.setCacheable(true);

        this.templateEngine = new TemplateEngine();
        this.templateEngine.setTemplateResolver(templateResolver);

        ...

    }

}

有许多配置TemplateEngine对象的方法,但是目前这几行代码将会教会我们足够多的需要的步骤。

Last updated