在使用 Spring 应用程序(和 spring boot,就此而言)苦苦挣扎了一段时间之后,看来我终于要让它工作了。
我已经完成了依赖解析和 Maven 构建。应用程序启动(而且非常快!)但是当我尝试访问
localhost:8080
每当我尝试访问应用程序的登录页面时,我都会收到以下浏览器消息:
HTTP Status 500 - Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "home/homeNotSignedIn", template might not exist or might not be accessible by any of the configured Template Resolvers
src/main/resources
文件夹是
src/main/resources
static // CSS, IMG and JS
templates // html
application.properties
log4j.properties
现在,我知道我可能会混合概念,但在我的 ApplicationConfiguration.java
上我有这个:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "b.c.g.c")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setTemplateMode("HTML5");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addDialect(new SpringSecurityDialect());
templateEngine.addDialect(new LayoutDialect(new GroupingStrategy()));
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;
}
// other beans
}
并且,在 application.properties
上,我有这个:
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
虽然我看到这些摘录讲述的是同一件事,但我敢打赌,对吧?
所以,实际上有两个问题,
1) 如何确保 Spring + Thymeleaf 知道在哪里可以找到模板?
2) 如何让应用程序响应 localhost:8080/appName
而不是 localhost:8080/
?
最佳答案
推荐方法
我先回答你的第二个问题
您已经在 src/main/resources 中定义了 application.properties 或 application.yml(Yaml 更好)文件。 Spring-Boot 自带 default properties文件,您可以在其中设置上下文路径(查找 webproperties),移植所有内容。
server.context-path=/<appname>
要回答你的第二个问题 spring-boot 你可以引用属性文件中的 thymeleaf 配置。
关于java - spring boot - 如何正确定义模板位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262370/