我在配置 Spring Boot 以使用 thymeleaf 并仍然提供静态内容时遇到了问题。我的资源目录中有两个目录:“/static”和“/templates”。根据 Spring Boot 文档,thymeleaf 应该默认在 templates 目录中找到 thymeleaf 模板。但是,当我尝试使用模板时收到 404。
来 self 的 Controller 的相关代码:
@RequestMapping("/")
public ModelAndView index() {
return new ModelAndView("index.html");
}
@RequestMapping(value = "/test")
public ModelAndView test() {
return new ModelAndView("test");
}
index.html 在 resources/static 中,test.html 在 resources/templates 中。
index.html 工作正常,但如果您尝试在浏览器中打开/test,它会抛出 404 提示找不到 thymeleaf 模板。
非常感谢任何帮助。我很难过。
最佳答案
任何未通过 ThymeleafViewResolver(您的/resources/static)的页面都需要删除。
/**
* Configures a {@link ThymeleafViewResolver}
*
* @return the configured {@code ThymeleafViewResolver}
*/
@Bean
public ThymeleafViewResolver thymeleafViewResolver()
{
String[] excludedViews = new String[]{
"/resources/static/*"};
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
/*
* This is how we get around Thymeleaf view resolvers throwing an error instead of returning
* of null and allowing the next view resolver in the {@see
* DispatcherServlet#resolveViewName(String, Map<String, Object>, Locale,
* HttpServletRequest)} to resolve the view.
*/
resolver.setExcludedViewNames(excludedViews);
return resolver;
}
关于spring - 使用 Spring Boot 与 thymeleaf 模板一起提供静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307745/