【问题标题】:Serving static content alongside thymeleaf templates with Spring Boot使用 Spring Boot 与 thymeleaf 模板一起提供静态内容
【发布时间】:2014-06-12 00:45:07
【问题描述】:

我在配置 Spring Boot 以使用 thymeleaf 并仍然提供静态内容时遇到了麻烦。我的资源目录中有两个目录:“/static”和“/templates”。根据 Spring Boot 文档,thymeleaf 默认应该在模板目录中找到 thymeleaf 模板。但是,当我尝试使用模板时,我得到了 404。

来自我的控制器的相关代码:

@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 模板。

我非常感谢任何帮助。我被难住了。

【问题讨论】:

  • 请同时发布您的 thymeleaf 配置。
  • 能否请您发布您的 Spring Boot 配置?

标签: spring thymeleaf spring-boot


【解决方案1】:

需要删除任何未通过 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;
}

【讨论】:

    【解决方案2】:

    您是否尝试过只返回模板的字符串名称而不是 ModelAndview? 并按照documentation 中的说明对您的 ModelAttributes 进行注释?

    【讨论】:

      猜你喜欢
      • 2015-09-21
      • 2017-04-05
      • 2016-07-14
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 2015-06-21
      相关资源
      最近更新 更多