springmvc如何跑react
Spring MVC 与 React 集成方法
将 React 集成到 Spring MVC 项目中可以通过以下方式实现,分为开发模式和生产模式两种场景:
开发模式分离运行
在开发阶段,React 前端和 Spring MVC 后端可以独立运行:
- 使用
create-react-app或类似工具搭建 React 开发环境 - 通过
npm start运行 React 开发服务器(默认端口 3000) - Spring MVC 后端运行在另一个端口(如 8080)
- 在 React 的
package.json中配置代理:"proxy": "http://localhost:8080" - 这样 React 会自动将 API 请求转发到 Spring MVC 后端
生产模式整合部署
当需要将 React 打包后与 Spring MVC 一起部署时:
-
构建 React 生产包
npm run build这会生成静态文件到
build目录 -
将 React 构建结果复制到 Spring MVC

- 将
build目录内容复制到 Spring MVC 的src/main/resources/static目录 - 或配置 Spring 静态资源路径指向 React 构建目录
- 将
-
配置 Spring MVC 控制器
@Controller public class HomeController { @RequestMapping(value = {"/", "/{path:[^\\.]*}"}) public String forward() { return "forward:/index.html"; } }这个配置确保所有非静态资源请求都返回 React 的入口文件
-
配置跨域支持(如果前后端分离部署)

@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/") .allowedOrigins("*") .allowedMethods("*"); } }
前后端通信方式
-
REST API:Spring MVC 提供
@RestController处理数据请求 -
使用
axios或fetch在 React 中调用 API -
示例 React 组件调用 API:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState([]); useEffect(() => { axios.get('/api/data') .then(response => setData(response.data)); }, []); return ( <div> {data.map(item => ( <div key={item.id}>{item.name}</div> ))} </div> ); }
构建工具集成
对于更紧密的集成,可以考虑:
- 使用 Maven 或 Gradle 插件自动构建 React 项目
- 示例 Maven 配置:
<plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.12.1</version> <executions> <execution> <id>install node and npm</id> <goals> <goal>install-node-and-npm</goal> </goals> </execution> <execution> <id>npm install</id> <goals> <goal>npm</goal> </goals> </execution> <execution> <id>npm run build</id> <goals> <goal>npm</goal> </goals> <configuration> <arguments>run build</arguments> </configuration> </execution> </executions> </plugin>
这种集成方式可以在 Maven 构建过程中自动处理 React 项目的构建,确保前后端资源同步更新。






