【问题标题】:How to validate JSON request matched with model/dto entity?如何验证与模型/dto 实体匹配的 JSON 请求?
【发布时间】:2022-01-10 03:40:06
【问题描述】:

我在 Spring/JPA 中有一个简单的问题。据说,我有这种格式的请求:

model/BillDto.java

public class BillDto {
    private String desc;
    private Long id;
    private Integer amount;
    
    public BillDto(String desc, long id, int amount) {
        this.desc = desc;
        this.id = id;
        this.amount = amount;
    }
}

或作为这种json格式

{
    "desc": "String",
    "id": 0,
    "amount": 0
}

这是控制器

controller/BillController.java

@RequestMapping(method = RequestMethod.POST)
public void create(@RequestBody BillDto billDto) {
    billService.create(billDto); // some service to execute
}

但是,当我不小心以错误的格式请求时,生成的 SQL 将不会执行,因此它返回 500 代码。例如,

{
    "desc": "String",
    "id": 0
}

如何在最短的代码行中处理此错误?在将它传递给服务之前,如何验证 json 请求以匹配模型/dto?

【问题讨论】:

  • 句柄是什么意思?即使提交的请求(JSON)不完整,也要避免得到 500 代码?

标签: java json spring spring-boot


【解决方案1】:

您可以对带有@RequestBody 注释的BillDto 参数使用@Valid 注释。这将告诉 Spring 在进行实际方法调用之前处理验证。如果验证失败,Spring 会抛出一个MethodArgument NotValidException,默认情况下会返回一个 400 (Bad Request) 响应。

@RequestMapping(method = RequestMethod.POST)
public void create(@Valid @RequestBody BillDto billDto) {
    billService.create(billDto); // some service to execute
}

在 POST 或 PUT 请求中,当我们传递 JSON 负载时,Spring 会自动将其转换为 Java 对象,现在它可以验证生成的对象。

【讨论】:

  • 您还需要使用正确的验证注释标记您的 DTO。
猜你喜欢
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2022-07-05
  • 2019-06-07
  • 2022-01-16
相关资源
最近更新 更多