
本教程详细讲解如何使用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 2022");
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 2022","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 (
<div className="App">
<h1>城市污染数据查询</h1>
<form onSubmit={this.handleSubmit}>
<label>
城市:
<input
name="city"
type="text"
value={city}
onChange={this.handleInputChange}
/>
</label>
<br/>
<label>
州/省:
<input
name="state"
type="text"
value={state}
onChange={this.handleInputChange}
/>
</label>
<br/>
<label>
国家:
<input
name="country"
type="text"
value={country}
onChange={this.handleInputChange}
/>
</label>
<br/>
<button type="submit">查询</button>
</form>
{/* 结果展示区域 */}
{responseData && (
<div className="results-container">
<h2>查询结果:</h2>
<p><strong>日期:</strong> {responseData.date}</p>
<p><strong>二氧化氮 (NO2):</strong> {responseData.no2}</p>
<p><strong>PM10:</strong> {responseData.pm10}</p>
<p><strong>PM2.5:</strong> {responseData.pm2_5}</p>
</div>
)}
</div>
);
}
}
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数据,从而构建一个功能完善的动态数据查询应用。
以上就是React与Spring集成:构建动态数据查询与展示应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号