gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:35:05 25 4
gpt4 key购买 nike

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

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

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;
}
}

使用的 thymeleaft 版本是:

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

我阅读了文档,但仍未找到解决方案。任何人都可以给我一些帮助我的提示吗?

最佳答案

使用静态字段:

@WebListener
public class ThymeleafListener implements ServletContextListener {

public static TemplateEngine engine;

public void contextInitialized(ServletContextEvent sce) {
engine = ThymeleafUtil.getTemplateEngine(sce.getServletContext());
}

public void contextDestroyed(ServletContextEvent sce) {
}
}

关于java - 如何在 Java servlet 项目中重用 Thymeleaf 模板(没有 Spring),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com