首页 > 解决方案 > Thymeleaf 无法读取静态文件夹中的文件

问题描述

我正在使用 Spring Boot 制作博客应用程序,并将 Thymeleaf 作为模板引擎。问题是,突然间我无法加载静态文件夹下的任何文件。为了使用 css 样式,我只是将标签放在 html 中,但图像也是一个问题。首先,当加载 css 文件时,由于 MIME 异常,我的浏览器会阻止这些文件。有趣的是,在 springboot 初始化程序中创建的空项目中它工作正常,我还添加了相同的项目依赖项,如 spring boot 安全性等。更重要的是,我能够将谷歌字体加载为 type="text/css"。当我切换到 Visual Studio 代码时,我的 css 和 js 代码运行良好。我的文件夹结构对于 Spring Boot 项目是正常的,是在 Spring Boot 初始化程序中制作的。我的路径一定没问题,因为在具有相同 html css 文件的新项目中,我可以加载这些文件,但是当我添加我的整个项目时,它又被破坏了,并且在 google devtools 中出现了 http 405 错误。这是使用带有 commandLineRunner 和一些安全性的 h2 数据库的普通项目。项目https://github.com/orestwojtowicz/blog-spring/tree/backend

<link rel="stylesheet" th:href="@{css/main.css}
<link type="text"css" src="../static/css/main.css" rel="stylesheet" th:href="@{/css/main.css}
```[project structure][1]


  [1]: https://i.stack.imgur.com/E0uhs.png


UPDATE: I was able to get rid off MIME error by adding additional springBoot security configuration but all static files are still blocked HTTP 405 error.

@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**").anyRequest(); }


OK UPDATE v2.0, Now I know what is causing this issue. It is Controller....
@PostMapping
public String registerNewUser(@Valid User user, Model model, BindingResult bindingResult,
                              RedirectAttributes redirectAttributes) {

    if (bindingResult.hasErrors()) {
        model.addAttribute("user", user);
        // prevent from adding not complete user object
        model.addAttribute("validationErrors", bindingResult.getAllErrors());

        return "auth/register";
    } else {

    }
    User newUser = userEntityService.registerNewUser(user);
    redirectAttributes.addAttribute("id", newUser.getId())
            .addFlashAttribute("success", true);



    return "redirect:/register";
}

我现在知道为什么这种方法会导致这个问题,但很快就会解决这个问题。

PROBLEM SOLVED
I should use     @PostMapping("/register") instead of @PostMapping....

标签: javahtmlspringthymeleaf

解决方案


推荐阅读