IDEA 中 Tomcat 部署 React + Java 前后端联动方案

一、核心思路
  1. 前端构建:将 React 项目编译为静态文件
  2. 后端集成:将静态文件嵌入 Java 项目资源目录
  3. Tomcat 部署:通过 Tomcat 统一服务前后端
  4. API 联动:前端通过相对路径访问后端接口
二、详细步骤
1. React 前端处理
# 在 React 项目根目录执行
npm run build

生成 build 目录(包含静态资源)

2. Java 后端集成静态文件
  • Spring Boot 项目
    build 目录内容复制到:
    src/main/resources/static/

  • 传统 Servlet 项目
    复制到 src/main/webapp/

3. 后端 API 接口示例
@RestController
@RequestMapping("/api")
public class DataController {
    
    @GetMapping("/data")
    public ResponseEntity<Map<String, String>> getData() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "后端数据");
        return ResponseEntity.ok(response);
    }
}

4. 前端 API 调用示例
// React 组件中调用
const fetchData = async () => {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    console.log("收到后端数据:", data);
  } catch (error) {
    console.error("请求失败:", error);
  }
}

5. IDEA 配置 Tomcat
  1. 添加配置
    Run → Edit Configurations → + → Tomcat Server → Local

  2. 部署设置
    Deployment → + → Artifact → 选择 war 包

  3. 端口配置
    HTTP port: 8080(默认)

6. 启动流程
  1. 编译 Java 项目生成 war 包
  2. 启动 Tomcat 服务器
  3. 访问 http://localhost:8080/
三、关键配置说明
  1. 跨域处理(开发阶段需要):

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowedMethods("*");
        }
    }
    

  2. 路径匹配规则

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            // 所有非API路径返回前端页面
            registry.addViewController("/{path:[^\\.]*}")
                    .setViewName("forward:/index.html");
        }
    }
    

四、验证方式
  1. 前端验证:浏览器访问 http://localhost:8080/
  2. API 验证:直接访问 http://localhost:8080/api/data
  3. 联动测试:前端页面触发 API 请求查看控制台输出

注意事项

  1. 每次修改前端后需重新执行 npm run build
  2. 确保后端打包包含最新静态资源
  3. 生产环境建议配置 Nginx 处理静态文件缓存
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐