必须放 src/main/resources/static,绝对不能放 templates;因为 static 是 Spring Boot 默认静态资源目录,支持 URL 与目录结构 1:1 映射,而 templates 专用于模板引擎渲染,放入 CSS/JS 会导致 404。

Bootstrap 文件该放 src/main/resources/static 还是 templates?
必须放 src/main/resources/static,绝对不能放 templates。Spring Boot 默认把 static 目录作为静态资源根路径,浏览器请求 /css/bootstrap.min.css 会直接映射到该目录下的对应文件;而 templates 是 Thymeleaf/Freemarker 等模板引擎的渲染目录,放进去的 CSS/JS 会被当成模板处理,返回 404 或原始 HTML 源码。
常见错误现象:
- 页面样式全无,浏览器开发者工具 Network 标签里显示
bootstrap.min.css返回 404 - 用 Thymeleaf 的
th:replace引入布局,但 CSS 不生效 —— 很可能是因为误删了spring-boot-starter-thymeleaf依赖,却还保留着th:href写法
正确做法:
- 在
src/main/resources/static下建css/、js/子目录,分别放入bootstrap.min.css和bootstrap.bundle.min.js - 若用 CDN,直接写
,但离线环境会失效
Thymeleaf 中怎么安全引入 Bootstrap 资源?
别硬写 。这种写法在部署到子路径(比如 /myapp)时会 404,因为没考虑 context-path。
要用 Thymeleaf 提供的资源解析语法:
- CSS:
- JS:
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
这样 Thymeleaf 会自动拼接当前应用的 context-path,确保 URL 正确。
注意:Bootstrap 5 已移除 jQuery 依赖,如果项目中还有 $().modal() 这类写法,浏览器控制台会报 ReferenceError: $ is not defined。要么降级到 v4,要么改用原生 JS 调用,例如 new bootstrap.Modal(...)。
启用 Spring Security 后,Bootstrap 静态资源打不开怎么办?
Spring Security 默认拦截所有请求,包括 /css/**、/js/** 这些静态路径。不放行,浏览器就加载不了 Bootstrap 文件。
必须在 Security 配置中显式放行:
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/css/**", "/js/**", "/images/**").permitAll()
.anyRequest().authenticated()
);
关键点:
-
requestMatchers必须写在anyRequest().authenticated()之前,顺序错会导致规则不生效 - 如果用了自定义静态路径(如通过
spring.web.static-path-pattern=/assets/**),放行路径也要同步改成/assets/** - 图片上传后存的是相对路径(如
upload/head-123.jpg),前端拼 URL 时也得走静态资源路径,所以upload/目录也建议一并放行
为什么上传头像后页面图片空白?
这不是 Bootstrap 的问题,而是静态资源映射和路径拼接没对齐。典型场景:后端用 MultipartFile 把头像存到 upload/ 目录,数据库只存了 head-123.jpg;前端却拼成 http://localhost:8080/head-123.jpg,而不是 http://localhost:8080/upload/head-123.jpg。
解决方法分两步:
- 后端配置静态资源映射:在
application.yml加上spring.resources.static-locations=classpath:/static/,file:upload/ - 前端 img 标签的 src 必须带前缀:
容易被忽略的细节:Windows 和 Linux 路径分隔符不同,file:upload/ 在 Windows 下要写成 file:upload\ 才能生效;更稳妥的做法是统一用正斜杠,并确保启动时有读写权限。











