要实现 “只启动 Spring Boot 后端,就能访问前端页面”,核心是将前端打包好的dist
目录下的静态资源(HTML、CSS、JS、图片等),放到 Spring Boot 默认的静态资源扫描目录中。以下是具体配置方案:
Spring Boot 启动时,会自动扫描并加载以下 4 个目录下的静态资源(优先级从高到低),直接将dist
的内容放入其中即可:
目录路径(相对项目根目录) | 说明 | 推荐程度 |
---|---|---|
src/main/resources/static/ | 最常用的静态资源目录,无特殊需求首选 | ★★★★★ |
src/main/resources/public/ | 次选目录,功能与static 一致 | ★★★☆☆ |
src/main/resources/resources/ | 目录名易与 “resources 根目录” 混淆,慎用 | ★★☆☆☆ |
src/main/resources/META-INF/resources/ | 通常用于第三方 jar 包的静态资源,自研项目极少用 | ★☆☆☆☆ |
static
目录为例)关键:不要将dist文件夹本身
放入static
,而是将dist内的所有文件
直接复制到static
目录下。
dist
的典型结构假设前端打包后,dist
目录内的文件如下:
dist/
├─ index.html (前端入口页面,必须有)
├─ css/ (样式文件目录)
│ └─ app.css
├─ js/ (脚本文件目录)
│ └─ app.js
└─ img/ (图片等资源目录)
└─ logo.png
static
目录后最终 Spring Boot 项目的资源目录结构应如下:
your-springboot-project/
└─ src/
└─ main/
└─ resources/
├─ application.properties (Spring Boot配置文件)
└─ static/ (静态资源目录,放入dist的所有内容)
├─ index.html (直接放,不是static/dist/index.html)
├─ css/
│ └─ app.css
├─ js/
│ └─ app.js
└─ img/
└─ logo.png
启动 Spring Boot 后端:运行 Spring Boot 主类(带@SpringBootApplication
注解的类)。
访问前端页面
:打开浏览器,输入后端服务的地址(默认端口为 8080,可在application.properties
中通过server.port
修改):
http://localhost:8080
(Spring Boot 会自动找到static
下的index.html
作为默认首页)。#/home
),直接访问http://localhost:8080/#/home
即可。如果前端使用History 模式路由(如 Vue Router 的mode: 'history'
),直接访问子路由(如http://localhost:8080/home
)会出现 404 错误(因为后端无法识别前端路由)。此时需在 Spring Boot 中添加路由转发配置,将所有非 API 请求转发到index.html
。
WebConfig
),实现WebMvcConfigurer
接口:import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 将所有非API的GET请求,转发到/index.html(前端负责路由解析)
// 若后端API有统一前缀(如/api),可排除/api路径,避免API请求被转发
registry.addViewController("/**")
.setViewName("forward:/index.html")
.setOrder(Ordered.LOWEST_PRECEDENCE); // 确保优先级低于API路由
}
}
/home
、/user
)转发到index.html
,由前端路由接管解析,避免 404。dist
内的所有文件复制到src/main/resources/static/
,启动后端后访问http://localhost:端口
即可。index.html
。这种方式本质是让 Spring Boot 作为 “静态资源服务器” 托管前端文件,无需额外启动 Nginx 等前端服务器,适合开发环境或小型项目部署。