首页 文章

使用Spring Boot在thymeleaf模板旁边提供静态内容

提问于
浏览
2

我在制作Spring Boot以使用百日咳但仍然提供静态内容方面遇到了麻烦 . 我的资源目录中有两个目录:“/ static”和“/ templates” . 根据Spring Boot文档,thymeleaf默认情况下应该在templates目录中找到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工作正常,但如果你试图在你的浏览器中打开/测试,它会抛出404说无法找到百日咳模板 .

我非常感谢任何帮助 . 我很难过 .

2 回答

  • 0

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

  • 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;
    }
    

相关问题