编程语言
首页 > 编程语言> > java – Spring Thymeleaf TemplateResolver错误

java – Spring Thymeleaf TemplateResolver错误

作者:互联网

我试图在春天使用百里香叶来定位文本字符串.我的html模板位于/ src / main / resources / templates /

所以我有:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    public MvcConfig() {
        super();
    }

    @Override
    public void addViewControllers(final ViewControllerRegistry registry)             {
        super.addViewControllers(registry);
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/sorting").setViewName("sorting");
    }

    @Override
    public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/","/resource/*");
        registry.addResourceHandler("/assets/**")
    .addResourceLocations("classpath:/assets/");
        registry.addResourceHandler("/css/**")
    .addResourceLocations("/css/");
    }


    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setCacheable(false);
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

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

但是模板解析器找不到我的模板,我收到一条错误消息:

Error resolving template “index”, template might not exist or might not be accessible by any of the configured Template Resolvers

我怀疑这是由于行中的路径不正确:templateResolver.setPrefix(“classpath:/ templates /”);但我无法找到应该去那里的前缀.

似乎大多数示例都将模板放在WEB-INF下.这是我应该遵循的推荐方式吗?

解决方法:

您需要使用ClassLoaderTemplateResolver.您的templateResolver()方法应如下所示.

@Bean
public TemplateResolver templateResolver() {
        TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("templates/");
        templateResolver.setCacheable(false);
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }

标签:java,spring,spring-mvc,thymeleaf,template-engine
来源: https://codeday.me/bug/20190724/1524225.html