Spring 启动 - Thymeleaf 模板 - 多个解析器

Spring boot - Thymeleaf template - multiple resolvers

我们的项目中有多个 thmeleaf 模板解析器。

我们的项目结构,

/src/main/java/*.java
/src/main/resources/pages/*.html
/src/main/resources/templates/*.html

在资源里面,我们有 pages 和 templates 文件夹。

因此,必须再添加一个视图解析器才能在页面中包含 html 个文件。

@Configuration
public class ThymeleafConfig {

    @Autowired
    private SpringTemplateEngine templateEngine;

    @PostConstruct
    public void init() {
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();

        resolver.setPrefix("pages/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("LEGACYHTML5");
        resolver.setOrder(templateEngine.getTemplateResolvers().size());

        templateEngine.addTemplateResolver(resolver);
    }

}

现在,想将几个文件移动到 /srs/main/webapp/

/src/main/resources/
/src/main/webapp/*.html

所以,尝试使用上面的配置文件,

resolver.setPrefix("webapp/");

也尝试了下面的代码,

 resolver.setPrefix("/webapp/");

现在,出现以下错误。

2015-10-27 15:36:13.078 [http-nio-8080-exec-8] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][http-nio-8080-exec-8] Exception processing template "agent": Error resolving template "agent", template might not exist or might not be accessible by any of the configured Template Resolvers
2015-10-27 15:36:13.094 [http-nio-8080-exec-8] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "agent", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "agent", template might not exist or might not be accessible by any of the configured Template Resolvers
    at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]

要为 webapp 文件夹完成的任何其他配置...

将 ClassLoaderTemplateResolver 更改为 ServletContextTemplateResolver 解决了问题。估计是出于安全原因,ClassLoaderTemplateResolver无法读取webapp下的文件。

@PostConstruct
    public void init() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();

        resolver.setPrefix("/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("LEGACYHTML5");
        resolver.setOrder(templateEngine.getTemplateResolvers().size());

        templateEngine.addTemplateResolver(resolver);
    }