You need to enable JavaScript to run this app. 如何使用RestTemplate更新ceiling列表值及解决id参数缺失报错
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 20:39:00