愤血冒 发表于 2025-6-8 12:05:39

Springboot6.x配置thymeleaf的可能bug

很久没有搞springboot的配置了。
业务需要,需要通过后端提供模板引擎服务(对于小型项目,这个比前后分离的好太多了)。
但是非常操蛋的是,总是提示模板引擎解析失败,无法找到资源。折腾了好半天!
框架说明
springboot版本-3.4.3
JAVA-JDK17
 
如果是开发环境,例如eclipse,idea,vscode中都是很好,没有任何问题,但是一旦打成jar运行,就会提示找不到资源!
依稀记得一点:如果实现了WebMvcConfigurer,那么在applicaton.yml做的一些配置可能就有问题。
于是使用java代码定义模板引擎,如下:
/**
       * thymeleaf 模板解析器
       * @return
       */
        @Bean
        public ITemplateResolver templateResolver() {
                SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
                resolver.setPrefix("classpath:/static/");
                resolver.setSuffix(".html");
                resolver.setTemplateMode("HTML");
                resolver.setCharacterEncoding("UTF-8");
                resolver.setCacheable(false);
                return resolver;
        }

        /**
       * spring模板引擎
       * @param templateResolver
       * @return
       */
        @Bean
        public TemplateEngine templateEngine(ITemplateResolver templateResolver) {
                SpringTemplateEngine templateEngine = new SpringTemplateEngine();
                templateEngine.setTemplateResolver(templateResolver);
                return templateEngine;
        }并把application.yml中的部分注释掉:

 
重启,依然提示:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource ")
看起来好像路径有问题,于是抱着试一试的心态,修改了java代码:
@RequestMapping("/catch")
public ModelAndView catch(
        @RequestParam(value="code",required=false) String code                
        ) {
        //ModelAndView mv=new ModelAndView("/catch/catch-index.html");       
        ModelAndView mv=new ModelAndView("catch/catch-index.html");       
        return mv;
}结果居然可以了!
只能这么总结:
1.如果实现了WebMvcConfigurer,那么就不要在yml中配置thymeleaf
2.在返回ModelAndView的代码中,路径最前面不要加/
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Springboot6.x配置thymeleaf的可能bug