使用JSON发送PUT请求时数据为null的问题排查求助
问题根源
你当前的接口方法用的是@RequestParam注解,这个注解专门用来从URL查询参数或表单数据里提取参数值,完全不会读取JSON请求体的内容。所以当你用JSON请求体传参时,price等所有参数都会是null,调用productService.updateProduct()时自然触发空指针异常,也就是你看到的Cannot invoke "java.lang.Double.doubleValue()" because "price" is null错误。
解决方案
要接收JSON请求体的参数,得用@RequestBody注解配合数据传输对象(DTO)来实现:
1. 创建ProductUpdateDTO类
用这个类封装JSON请求体里的所有可选更新字段:
public class ProductUpdateDTO { private String title; private Double price; private String description; private String category; private String image; // Spring解析JSON必须要有无参构造器 public ProductUpdateDTO() {} // 生成所有字段的getter和setter方法 public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
如果你用Lombok,直接加
@Data注解就能替代手动写getter/setter和构造器,代码会更简洁。
2. 修改Controller接口方法
把原来的多个@RequestParam参数替换为@RequestBody ProductUpdateDTO,同时保留路径参数:
@PutMapping(path = "/{productId}") public void updateProduct( @PathVariable("productId") Long productId, @RequestBody ProductUpdateDTO updateDTO ) { productService.updateProduct( productId, updateDTO.getTitle(), updateDTO.getPrice(), updateDTO.getDescription(), updateDTO.getCategory(), updateDTO.getImage() ); }
3. 优化Service层(可选)
也可以让Service层直接接收DTO对象,让代码更简洁:
// Service层示例代码 public void updateProduct(Long productId, ProductUpdateDTO updateDTO) { // 先查询要更新的产品(这里假设用JPA) Product product = productRepository.findById(productId) .orElseThrow(() -> new RuntimeException("未找到对应产品")); // 只更新非空的字段 if (updateDTO.getTitle() != null) { product.setTitle(updateDTO.getTitle()); } if (updateDTO.getPrice() != null) { product.setPrice(updateDTO.getPrice()); } if (updateDTO.getDescription() != null) { product.setDescription(updateDTO.getDescription()); } if (updateDTO.getCategory() != null) { product.setCategory(updateDTO.getCategory()); } if (updateDTO.getImage() != null) { product.setImage(updateDTO.getImage()); } productRepository.save(product); }
修改完成后,你之前的JSON格式PUT请求就能正常执行了,Spring会自动把JSON请求体解析为ProductUpdateDTO对象,参数也能正确传递到Service层。
内容的提问来源于stack exchange,提问作者BabouG
相关产品推荐
相关产品推荐

