本教程详细讲解如何使用react前端与spring boot后端构建一个简单的web应用。核心内容包括:react组件如何通过表单收集用户输入,利用axios发送get请求到spring `@getmapping` 端点,该端点接收 `@requestparam` 参数并返回json数据。教程重点演示如何在react中正确处理异步api响应,将完整的json数据存储到组件状态中,并有效地解析和展示这些数据,从而实现前后端的数据交互与动态展示。
在现代Web开发中,前后端分离是常见的架构模式。本教程将指导您如何结合React作为前端框架,以及Spring Boot作为后端服务,构建一个能够接收用户输入、调用后端API并展示动态数据的简单应用。我们将重点关注如何在React中正确处理表单提交、异步请求以及JSON数据的解析与展示。
首先,我们来看后端Spring Boot服务的实现。它负责接收来自前端的请求,处理业务逻辑(在此示例中是调用pollutionService),并返回JSON格式的数据。
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PollutionController {
// 假设 pollutionService 已经注入并提供了获取污染数据的方法
// private final PollutionService pollutionService;
@GetMapping("/pollution/current/city")
public JSONObject getCurrentPollutionDataByCityStateCountry(
@RequestParam(value = "city") String city,
@RequestParam(value = "state") String state,
@RequestParam(value = "country") String country
) {
try {
// 实际应用中这里会调用服务层获取数据
// return pollutionService.getCurrentPollutionDataByCityStateCountry(city, state, country);
// 模拟数据返回
JSONObject response = new JSONObject();
response.put("date", "Tue Dec 06 22:13:32 CET 2025");
response.put("no2", "48.67");
response.put("pm10", "9.51");
response.put("pm2_5", "5.85");
return response;
} catch (Exception e) {
e.printStackTrace();
return new JSONObject(); // 发生异常时返回空JSON对象
}
}
}后端说明:
示例响应:
{"date":"Tue Dec 06 22:13:32 CET 2025","no2":"48.67","pm10":"9.51","pm2_5":"5.85"}React前端负责渲染表单、收集用户输入、发送HTTP请求到Spring后端,并展示后端返回的数据。
我们将使用一个类组件App来管理表单的输入状态和从后端获取的数据。
import React, { Component } from 'react';
import './App.css';
import axios from 'axios'; // 引入axios用于HTTP请求
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: 'New York',
state: 'New York', // 注意:这里命名为state以匹配后端参数,原问题中是province
country: 'US',
responseData: null // 用于存储后端返回的完整JSON数据
};
// 绑定事件处理器的this上下文
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// 处理表单输入变化的通用方法
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name; // input元素的name属性与state中的键对应
this.setState({
[name]: value // 使用计算属性名更新对应的state
});
}
// 处理表单提交
handleSubmit(event) {
event.preventDefault(); // 阻止表单默认提交行为,避免页面刷新
// 构建请求URL
const apiUrl = `http://localhost:8080/pollution/current/city?city=${this.state.city}&state=${this.state.state}&country=${this.state.country}`;
// 使用axios发送GET请求
axios.get(apiUrl)
.then(response => {
// 将后端返回的完整数据对象存储到state中
this.setState({ responseData: response.data });
// 在异步请求成功并更新state后,才能访问到最新的responseData
// console.log("Response Data:", response.data); // 可以用于调试
alert('数据已成功获取!请查看结果区域。');
})
.catch(error => {
console.error("请求失败:", error);
alert('获取数据失败,请检查控制台。');
});
}
render() {
// 从state中解构出数据,方便在渲染时使用
const { city, state, country, responseData } = this.state;
return (
城市污染数据查询
{/* 结果展示区域 */}
{responseData && (
日期: {responseData.date}
二氧化氮 (NO2): {responseData.no2}
PM10: {responseData.pm10}
PM2.5: {responseData.pm2_5}
)} ); } } export default App;a. 状态管理 (this.state)
b. 输入处理 (handleInputChange)
这是一个通用的事件处理器,通过event.target.name和event.target.value动态更新state中对应的字段。这使得您可以为多个输入字段使用同一个处理器,保持代码简洁。
c. 表单提交与API请求 (handleSubmit)
d. 结果展示 (render 方法)
import org.springframework.web.bind.annotation.CrossOrigin;
// ...
@CrossOrigin(origins = "http://localhost:3000") // 允许React应用访问
@GetMapping("/pollution/current/city")
public JSONObject getCurrentPollutionDataByCityStateCountry(...) {
// ...
}
辑封装到单独的服务模块中,而不是直接放在组件内部。通过本教程,您应该已经掌握了如何使用React与Spring Boot进行前后端数据交互的基本流程,特别是如何正确处理异步请求和JSON数据,从而构建一个功能完善的动态数据查询应用。