You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot @PutMapping接口如何在Service层获取Request DTO参数

问题解决方案

核心问题是你当前的Service接口仅接收了id参数,没有把Controller层拿到的ProgramRequestDto请求体传入Service,所以Service内部自行实例化的空DTO对象无法获取前端传递的参数值。按照以下步骤修改即可:

1. 修改Service接口定义

新增ProgramRequestDto类型的入参,同时把方法名调整为小驼峰格式(符合Java编码规范):

Program update(Long id, ProgramRequestDto programRequestDto) throws UpdateDataException;

2. 修改Controller层调用逻辑

将请求体中拿到的programRequestDto传递给Service方法:

@PutMapping(value = "/edit-program/test/{id}")
public ResponseEntity<ProgramResponseDto> updateProgramByIdTest (
        @PathVariable(value = "id") final Long id,
        @Valid @RequestBody final ProgramRequestDto programRequestDto) throws UpdateDataException {

    ProgramResponseDto programResponseDto = ProgramMapper.INSTANCE.programToProgramResponseDTO(
            programService.update(id, programRequestDto));

    log.info(LocaleContext.format("response.success",
            (new Object() {
            }.getClass().getEnclosingMethod().getName()),
            HttpStatus.OK.toString()));

    return status(HttpStatus.OK).body(programResponseDto);
}

3. 修改Service实现类逻辑

删除自行实例化空DTO的代码,直接使用传入的DTO赋值,同时补充参数校验逻辑避免数据异常:

@Override
public Program update(Long id, ProgramRequestDto programRequestDto) throws UpdateDataException {
    Optional<Program> programDB = programRepository.findById(id);
    if (programDB.isEmpty()) {
        throw new UpdateDataException("对应id的节目数据不存在");
    }
    Program program = programDB.get();
    // 可选校验:避免路径id和请求体id不一致导致的逻辑错误
    if (!id.equals(programRequestDto.getId())) {
        throw new UpdateDataException("路径id与请求体id不匹配");
    }
    program.setProgram(programRequestDto.getProgram());
    // 主键id无需修改,可省略setId步骤
    try {
        return programRepository.save(program);
    } catch (Exception e){
        throw new UpdateDataException("数据更新失败:" + e.getMessage());
    }
}

可选优化建议

  • 如果后续字段增多,可在Mapper中新增属性拷贝方法,直接把DTO的属性覆盖到查询到的实体对象上,无需手动逐个set字段,简化代码
  • 异常提示建议补充业务语义,方便排查问题

内容的提问来源于stack exchange,提问作者Supersan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:36:05