如何使用RestTemplate更新ceiling列表值及解决id参数缺失报错
问题解决方案
1. 直接修复当前报错
你当前遇到的MissingServletRequestParameterException报错,核心原因是参数注解使用错误:
@PutMapping("/update/{id}")中定义的
id是路径变量,不是URL后缀的查询参数,不能用@RequestParam注解绑定,需要替换为@PathVariable注解。
将控制器方法的参数定义从:
public Ceiling update(@RequestParam Integer id, Card card)
修改为:
public Ceiling update(@PathVariable Integer id, @RequestBody Card card)
即可解决当前参数缺失的报错,额外添加@RequestBody是为了让Spring正确把请求体的JSON数据绑定到Card对象上。
2. 修复其他逻辑错误
你现有代码还存在多处逻辑问题,会导致后续更新ceiling失败,完整修正后的代码如下:
@PutMapping("/update/{id}") public Ceiling update(@PathVariable Integer id, @RequestBody Card card){ // 1. 查询所有卡片列表 ParameterizedTypeReference<List<Card>> responseType = new ParameterizedTypeReference<List<Card>>() {}; // 原代码第三个参数错误传了未初始化的resp,无请求头/体时填null即可 ResponseEntity<List<Card>> resp = restTemplate.exchange(GET_CARD, HttpMethod.GET, null, responseType); List<Card> cardList = resp.getBody(); if (cardList == null || cardList.isEmpty()) { return null; } // 2. 筛选对应ID的目标卡片 Card targetCard = cardList.stream() .filter(c -> id.equals(c.getId())) .findFirst() .orElse(null); if (targetCard == null) { return null; } // 3. 更新ceiling字段,可根据业务调整更新规则 targetCard.setCeiling(card.getCeiling()); // 4. 调用卡片更新接口回写修改后的数据,UPDATE_CARD_URL替换为实际的更新接口地址 HttpEntity<Card> requestEntity = new HttpEntity<>(targetCard); restTemplate.exchange(UPDATE_CARD_URL, HttpMethod.PUT, requestEntity, Card.class); // 5. 返回更新后的ceiling数据 return targetCard.getCeiling().get(0); }
3. 请求调用说明
发起PUT请求时需要符合以下规则:
- 请求路径示例:
PUT http://你的服务地址/update/1,路径末尾的数字就是要更新的卡片ID - 请求头添加
Content-Type: application/json - 请求体传入带新ceiling值的卡片JSON结构即可
内容的提问来源于stack exchange,提问作者lamyaa
相关产品推荐
相关产品推荐

