/css/style.css返回404是因为请求路径与资源映射不匹配:文件必须置于src/main/resources/static/css/style.css,禁用@enablewebmvc,且html中引用为"/css/style.css"而非"/static/css/style.css"。

为什么/css/style.css 返回 404
不是 Spring Boot “不支持 CSS”,而是请求路径和资源映射没对上——浏览器发的是 /css/style.css,但 Spring Boot 没在对应 classpath 路径下找到它,或根本没启用该路径的映射。
常见卡点:
- 文件实际放在
src/main/resources/css/style.css(漏了static),正确位置必须是src/main/resources/static/css/style.css - IDE 没自动构建资源:IntelliJ 需勾选 Build project automatically,或手动执行
Maven → Resources → copy-resources - 加了
@EnableWebMvc注解:它会直接关闭所有默认静态资源配置,包括/static映射 - 自定义了
WebMvcConfigurer但没调用super.addResourceHandlers(registry),导致默认四个 classpath 路径(/static、/public、/resources、/META-INF/resources)全被清空
Thymeleaf 中怎么写 CSS 引入路径
别写 <link href="/static/css/style.css"> ——这是错的。/static/ 是 classpath 目录名,不是 URL 路径前缀。
Thymeleaf 正确写法是:
-
<link th:href="@{/css/style.css}" rel="stylesheet">(推荐,自动处理上下文路径) - 或纯 HTML:
<link href="/css/style.css" rel="stylesheet">(/表示应用根路径,如http://localhost:8080/) - 绝对路径写法
href="css/style.css"也行,但依赖当前页面 URL;比如访问/user/list时,浏览器会请求/user/css/style.css,容易出错
spring.mvc.static-path-pattern 是干啥的
它不是“让 CSS 生效”的开关,而是给所有静态资源 URL 统一加前缀。
例如设成 spring.mvc.static-path-pattern=/res/** 后:
- 原本能通过
/css/style.css访问的文件,现在必须写成/res/css/style.css - 设成
/static/**反而会让/css/style.css失效,且/static/并不对应磁盘上的static文件夹 - 除非你明确需要统一前缀(比如做 CDN 分离或 API 网关路由),否则不要动这个配置
什么时候才要改 spring.web.resources.static-locations
只在两类真实需求下才需要改:
- 想把静态资源从
classpath:/static/换到别的 classpath 目录,比如classpath:/assets/,就配spring.web.resources.static-locations=classpath:/assets/ - 要接入外部磁盘路径(如用户上传图片),比如
file:/data/uploads/,就配成spring.web.resources.static-locations=classpath:/static/,file:/data/uploads/ - 注意:
spring.resources.static-locations在 Spring Boot 2.6+ 已弃用,必须用spring.web.resources.static-locations
最容易被忽略的是 IDE 构建行为和 @EnableWebMvc 的全局影响——哪怕只加了一行注解,整个静态资源链就断了;而路径写错时,浏览器地址栏里多打一个 /static 看似合理,其实完全违背 Spring Boot 的 URL 映射逻辑。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











