如何在Java servlet项目中重用Thymeleaf模板(没有Spring)

时间:2018-04-10 16:20:51

标签: java thymeleaf

如何在Java servlet项目中重用Thymeleaf模板(没有 弹簧)?

我需要根据映射的路径更改片段。

servlet的方法doGet是:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    WebContext wContext = new WebContext(request, response, request.getServletContext(), request.getLocale());
    ITemplateEngine template = ThymeleafAppUtlil.getTemplateEngine(request.getServletContext());
    template.process("GenericTemplate", wContext,response.getWriter()); 
}

ThymeleafAppUtlil课程是:

import javax.servlet.ServletContext;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafAppUtlil {
    private ThymeleafAppUtlil() {
        super();
    }
public static TemplateEngine getTemplateEngine(ServletContext context) {
        TemplateEngine templateEngine;
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(context);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/templates/thymeleaf/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheTTLMs(0L);
        templateResolver.setCacheable(false);
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
}

使用的百日咳的版本是:

<dependency>
       <groupId>org.thymeleaf</groupId>
       <artifactId>thymeleaf</artifactId>
       <version>3.0.2.RELEASE</version>
</dependency>

我阅读了有关文档的内容,但仍未找到解决方案。有人可以给我一些帮助我的建议吗?

0 个答案:

没有答案