如何从React服务向Java Spring Boot控制器传递字符串参数?
问题原因与解决方案
核心问题
你的前端GET请求没有把id参数传递到后端,导致Spring控制器无法获取到值。
GET请求的参数传递逻辑和POST不同:POST通常把参数放在请求体里,但GET请求的标准做法是将参数作为查询参数(URL中?key=value的部分)或者路径变量传递,而你当前的fetch代码只是调用了接口基础URL,没有附加任何参数,所以后端的id自然为null。
修复方案
前端代码修改(两种可选方式)
方式1:使用查询参数(推荐,适配多参数场景)
用URLSearchParams构建查询参数,自动处理特殊字符编码,避免手动拼接URL的潜在问题:
getCustomerRentalsList(id) { console.log("getCustomerRentalsList FE service!!" + id); console.log("getCustomerRentalsList type on service: " + typeof(id)) const params = new URLSearchParams(); params.append('id', id); return fetch(`${RENTAL_API_BASE_URL}/getCustomerRentalsList?${params}`, { method: 'get', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-type': 'application/json', }, credentials: 'same-origin', }) .then(res => res.json()); }
方式2:使用路径变量(更符合RESTful风格,适合单个标识类参数)
如果调整接口设计为路径传参,前端直接将id拼入URL路径:
getCustomerRentalsList(id) { console.log("getCustomerRentalsList FE service!!" + id); console.log("getCustomerRentalsList type on service: " + typeof(id)) return fetch(`${RENTAL_API_BASE_URL}/getCustomerRentalsList/${id}`, { method: 'get', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-type': 'application/json', }, credentials: 'same-origin', }) .then(res => res.json()); }
后端代码对应调整
对应查询参数方式
给参数加上@RequestParam注解,明确指定从查询参数获取,还可以设置必填校验简化空值判断:
@GetMapping("/getCustomerRentalsList") public List<String> getCustomerRentalsList(@RequestParam(required = true) String id) { System.out.println("TEST ID: " + id); return service.getCustomerRentalsList(id); }
对应路径变量方式
修改注解为@PathVariable,同时调整接口路径匹配规则:
@GetMapping("/getCustomerRentalsList/{id}") public List<String> getCustomerRentalsList(@PathVariable String id) { System.out.println("TEST ID: " + id); return service.getCustomerRentalsList(id); }
关键知识点与学习方向
- HTTP请求参数传递规范:
- GET请求:参数优先放在查询参数或路径中,不依赖请求体(部分服务器框架不支持从GET请求体读取参数)。
- POST请求:参数可放在请求体(JSON/表单格式)或查询参数中,按需选择。
- Spring MVC参数绑定:
@RequestParam:用于提取URL查询参数。@PathVariable:用于提取URL路径中的动态变量。@RequestBody:用于解析请求体中的JSON/XML数据(POST/PUT请求常用)。
- Fetch API使用:
- 掌握GET请求的参数构建方式,熟练使用
URLSearchParams处理参数编码,避免手动拼接URL导致的错误。
- 掌握GET请求的参数构建方式,熟练使用
内容的提问来源于stack exchange,提问作者Zarkaylia
相关产品推荐
相关产品推荐

