【问题标题】:How to correct validate parameters from GET request in Spring Boot?如何在 Spring Boot 中更正来自 GET 请求的验证参数?
【发布时间】:2021-10-19 00:50:57
【问题描述】:

我有一个 GET 处理程序,我从带有 @RequestParam 注释的 URL 中获取 3 个参数:

@GetMapping
public String getStocks(@RequestParam(value = "color", required = true) String color,
                        @RequestParam(value = "op", required = true) String op,
                        @RequestParam(value = "size", required = true) Integer size) {

    return service.getStocks(color, op, size);
}

我需要对这些参数中的每一个进行大量验证,例如匹配正则表达式模式、范围等。我不能在前端做到这一点。
我尝试在 @RequestParam 之前使用注释来做到这一点,并且效果很好,但它看起来如此丑陋和凌乱,因为我需要在每个参数上添加很多它们。

是否有“正确的方法”来验证来自 GET 请求的参数,就像我们可以使用 DTO 和 POST 请求一样?

【问题讨论】:

  • 看来问题与请求参数中的自定义验证有关。如果是这样,这是一个被问到并得到很好回答的question

标签: java spring spring-boot spring-mvc


【解决方案1】:

@RequestParam(value = "color", required = true) 字符串颜色 不需要使用required=true,默认为true,required=false时需要指定。

您可以使用以下依赖项来验证输入。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

可以这样使用。

@RequestParam("size") @Min(5) int size

【讨论】:

  • 我需要在每个参数上使用许多注释,并且代码看起来很糟糕而且不清楚(看起来很糟糕)。当您使用带有 RequestParam 注释(而不是 RequestBody)的注释进行验证时,您必须在您的类上使用 Validated 注释,当参数未通过验证时,它会抛出 ConstraintViolationException 并导致 500 错误
猜你喜欢
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多