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

Spring Boot 2.7 RestController中Bad Request问题解决求助

解决Postman提交Customer返回Bad Request的问题

Bad Request(400)通常是请求数据不符合接口要求导致的,按以下步骤逐一排查:

1. 查看Postman的详细错误响应

在Postman的「Response」标签切换到「Body」,查看具体错误提示。Spring框架会返回明确的失败原因,比如:

  • JSON语法错误(逗号缺失、引号不匹配等)
  • 字段类型不匹配(如字符串传给Integer类型的id)
  • 校验规则未满足(若实体类添加了校验注解)

2. 检查请求JSON的格式与字段匹配

你的Customer实体字段为id、idCustomer、email、choices,请求JSON需严格对应:

  • 字段名大小写必须一致(不能写成idcustomer或Email)
  • 无需传递id(自增主键由数据库自动生成,手动传入可能引发冲突)
  • 若传递choices,需保证内部Choice对象结构正确(不要传customer字段,关联关系由JPA自动维护)

示例合法请求JSON:

{
  "idCustomer": "CUST001",
  "email": "test@example.com",
  "choices": [
    {
      "choiceName": "Option1"
    }
  ]
}

3. 排查实体校验逻辑

虽然当前Customer实体未加校验注解,但如果后续添加@NotBlank、@Email等规则,请求未满足时会触发400。同时确保校验功能正常生效:

  • 你已引入spring-boot-starter-validation依赖,校验功能默认开启
  • 若需强制必填字段,可给对应字段添加注解:
@NotBlank(message = "客户ID不能为空")
private String idCustomer;

@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;

4. 检查ModelMapper映射问题

你直接将请求的Customer实体映射为CustomerDto,需确保两者字段名、类型完全匹配:

  • 若CustomerDto与Customer字段不一致,ModelMapper可能无法正确映射,导致后续Service层处理异常
  • 建议将ModelMapper配置为Spring Bean,避免重复创建实例:
@Configuration
public class ModelMapperConfig {
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

然后在Controller中注入使用:

@Autowired
private ModelMapper modelMapper;

5. 排查Service层注入与逻辑问题

Controller中customer.addCustomer(customerDto)的customer对象,若未通过@Autowired注入Service实例,会引发空指针异常(返回500);若Service层对Dto校验失败返回400,也需检查Service逻辑:

  • 确保CustomerService被正确注入:
@Autowired
private CustomerService customerService;

// 调用Service方法
CustomerDto addCust = customerService.addCustomer(customerDto);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:15:36