【问题标题】:Unable to serve static resources with spring, receive index instead无法使用 spring 提供静态资源,而是接收索引
【发布时间】:2025-12-01 04:45:02
【问题描述】:

我有一个简单的 Spring Web 应用程序。

@Controller
public class GreetingController {

    @Autowired
    GreetingRepository repository;

    @GetMapping("/greeting")
    public String greetingForm(Model model) {
        model.addAttribute("greeting", new Greeting());
        return "greeting";
    }

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute Greeting greeting) {
        repository.save(greeting);
        return "result";
    }

}

HTML 是:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Greeting Sample</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
        <p>Id: <input type="text" th:field="*{id}" /></p>
        <p>Message: <input type="text" th:field="*{content}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

这是在 HTML 中引用的 css 文件:

p {
    color: #ff5588;
}

但是,没有应用 css。

实际上,当我查询 localhost:8080/css/style.css 时,它会返回索引页面的 HTML 内容。

【问题讨论】:

  • 您的项目是否有安全实现(SpringSecurity 或自定义)?如果是这样,您的用户是否有权访问 '/css/*' url 或者此 url 具有公共访问权限?如果用户无权访问 url 或处理请求时出现异常,则可能会发生重定向。
  • 原来是这样。你能把它作为答案发布吗?然后我可以投票并给你代表。
  • 我将其添加为答案。

标签: css spring-boot thymeleaf


【解决方案1】:

这可能是安全配置问题。您的项目是否有安全实现(SpringSecurity 或自定义)?如果是这样,您的用户是否有权访问 /css/* url 或此 url 具有公共访问权限?如果用户无权访问 url 或处理请求时出现异常,可能会发生重定向。

【讨论】:

    【解决方案2】:

    事实证明,安全配置阻止了对资源的所有请求。相反,它将这些请求重定向到索引页面(已配置)。

    解决方案很简单,授权对网站资源的所有请求(/images/**/css/**/js/**)。

    配置完成后,Web 应用程序按预期工作。

    【讨论】:

      最近更新 更多