TemplateEngine不在模板文件夹中查找文件

时间:2018-07-25 19:15:52

标签: java spring-boot thymeleaf

我正在构建一个SpringBoot应用程序,该应用程序从数据库中加载国际化消息。 (Followed this tutorial

由此,我必须创建一个ThymeleafConfiguration类并设置一个SpringTemplateEngine Bean。本教程仅给出了有关此配置的粗略想法(仅配置了消息源,但未配置其他模板引擎配置),因此它破坏了我的控制器页面呈现(控制器现在返回字符串而不是视图)。

我正在尝试配置其余的TemplateEngine(例如TemplateResolver,我认为这是渲染不正确的原因),但是,我不知道如何正确进行[我保持收到“模板解析期间发生错误(模板:“ ServletContext资源[/templates/login.html]”)“消息]。

如何正确配置SpringTemplateEngine?

到目前为止,我的配置:

@Configuration
public class ThymeleafConfiguration implements WebMvcConfigurer, ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Autowired
    private DatabaseMessageSource databaseMessageSource;

    @Bean
      public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(thymeleafTemplateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
      }

     private ITemplateResolver templateResolver() {
            SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
            resolver.setApplicationContext(applicationContext);
            resolver.setPrefix("/templates/");
            resolver.setSuffix(".html");
            resolver.setTemplateMode(TemplateMode.HTML);
            return resolver;
          }


    @Bean
    public SpringTemplateEngine thymeleafTemplateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        engine.setTemplateEngineMessageSource(databaseMessageSource);
        return engine;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }

}

控制器类:

 @Controller
    public class ApplicationController {


    @RequestMapping("/home")
    public String home() {
        return "/home.html";
    }


    @RequestMapping("/core/index")
    public String index() {
        return "/core/index.html";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

File structure

1 个答案:

答案 0 :(得分:1)

问题出在

private ITemplateResolver templateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/templates/"); // Here!!!
    resolver.setSuffix(".html");
    return resolver;
}

由于模板位于src / main / resources中,因此必须将其指向类路径,如下所示:

@Bean
public SpringResourceTemplateResolver templateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("classpath:/templates/"); // It works after adding 'classpath:'
    resolver.setSuffix(".html");
    return resolver;
}

此外,从接口到实现类的变化不大,应该不会干扰结果。