Spring Boot无法使用Java配置更改Thymeleaf模板目录
将Thymeleaf模板文件放在默认设置下src/main/resources/templates
对我来说可以。当我想重命名目录时,请说mytemplates
;这没用。
当应用程序启动时,我收到 找不到模板位置:classpath:/ templates /(请添加一些模板或检查您的Thymeleaf配置) 警告。
当我指向主页时,出现
org.thymeleaf.exceptions.TemplateInputException:解决模板“索引”时出错,该模板可能不存在,或者任何已配置的模板解析器
错误都 无法访问该模板 。
我使用以下Java配置:
package com.zetcode.conf;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver tres = new ClassLoaderTemplateResolver();
tres.setPrefix("classpath:/mytemplates/");
tres.setSuffix(".html");
tres.setCacheable(false);
tres.setTemplateMode("HTML5");
tres.setCharacterEncoding("UTF-8");
return tres;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Thymeleaf view resolver")
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setCache(false);
viewResolver.setOrder(1);
return viewResolver;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
}
我做错了什么?
回答:
尝试以下方法:
第一:在application.properties
文件中定义以下设置
spring.thymeleaf.templateResolverOrder=1
现在自定义您的实现。
@Beanpublic ClassLoaderTemplateResolver yourTemplateResolver() {
ClassLoaderTemplateResolver yourTemplateResolver = new ClassLoaderTemplateResolver();
yourTemplateResolver.setPrefix("yourTemplates/");
yourTemplateResolver.setSuffix(".html");
yourTemplateResolver.setTemplateMode(TemplateMode.HTML);
yourTemplateResolver.setCharacterEncoding("UTF-8");
yourTemplateResolver.setOrder(0); // this is iportant. This way spring
//boot will listen to both places 0
//and 1
emailTemplateResolver.setCheckExistence(true);
return yourTemplateResolver;
}
以上是 Spring Boot无法使用Java配置更改Thymeleaf模板目录 的全部内容, 来源链接: utcz.com/qa/419097.html