spring - 使用 Spring Boot 与 thymeleaf 模板一起提供静态内容

标签 spring thymeleaf spring-boot

我在配置 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/

相关文章:

javascript - Thymeleaf 在 Google Analytics 代码上抛出错误

html - 如何使用 thymeleaf 命名空间来包含页面的页眉和页脚而不使用任何模板解析器?

java - 处理 spring-boot 应用程序/外部配置的推荐方法?

java - 在 Tomcat 5.5 上运行应用程序

java - Spring data rest - 处理实体验证

java - 使用默认值声明 Thymeleaf 变量后如何对其进行算术运算?

java - Spring Boot - 依赖项的初始化顺序

spring-boot - 有什么理由不将小型 spring-boot 启动器与自动配置放在一起?

java - 除了log4j xml、属性文件和源代码(主要是java)之外,还有其他方式配置日志吗?

java - Spring、Hibernate : Retrieve Objects based upon date, 如果未找到,则为最近的日期