静态资源与首页

页面引用的 CSS、图片、JS 等静态文件无需写控制器,Spring Boot 按约定位置自动对外提供,还内置了欢迎页(首页)约定。

默认静态资源位置

Boot 默认按顺序从以下四个 classpath 位置查找静态资源,命中即返回:

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/

日常项目最常用 src/main/resources/static/。例如 static/css/app.css 可通过 http://localhost:8080/css/app.css 直接访问。

欢迎页约定

Spring Boot 支持「静态欢迎页」与「模板欢迎页」两种:

  • 静态方式:在 static 目录放一个 index.html,访问应用根路径 / 时自动返回它;
  • 模板方式:使用 Thymeleaf 等模板引擎时,把 templates/index.html 当作首页(见 11 章)。

注意:如果自己写了 @GetMapping("/") 处理根路径,控制器会优先接管,欢迎页约定不再生效。

自定义配置

几个常用配置项(以官方文档的属性清单为准,不同版本前缀可能有调整):

# 自定义静态资源目录(替换默认四处位置)
spring.web.resources.static-locations=classpath:/static/,file:/opt/app/static/
# 浏览器缓存时长(秒)
spring.web.resources.cache.period=3600
# 静态资源 URL 前缀(默认 /**)
spring.mvc.static-path-pattern=/static/**

示例:static 目录放一个欢迎页:

src/main/resources/static/index.html
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>示例应用</title>
</head>
<body>
    <h1>欢迎使用示例应用</h1>
    <p>更多内容见 <a href="/hello">/hello 接口</a></p>
</body>
</html>

启动后访问 http://localhost:8080/ 即可看到该页面。

小结

静态资源放对目录即可被直接访问;index.html 会变成站点首页。需要动态数据渲染页面时,进入下一章:Thymeleaf 模板引擎。

笔记加载中…