如何分组请求javax验证?

5sxhfpxr  于 2022-09-19  发布在  Java
关注(0)|答案(1)|浏览(150)

bounty在4天后到期。此问题的答案有资格获得+50声誉奖励。Pierre Recuay正在寻找来自可靠来源的答案:我理解这是一个不寻常的问题,但我非常感谢您的帮助。非常感谢。

我测试了spring boot starter验证行为,并注意到:请求主体首先通过抛出WebExchangeBindException进行验证,然后请求路径和查询参数通过抛出ConstraintViolationException进行验证。那么,如何在单个响应主体中捕获的单个异常中连接这两组约束?
预期React机构:

{
  "address": "must not be blank",
  "mail": "must be a well-formed email address",
  "floor": "floor cannot be null",
  "control.mark": "must be less than or equal to 5",
  "control.infect": "must be greater than 0",
  "control.age": "must be greater than or equal to 5"
}

实际请求正文字段约束:

{
  "address": "must not be blank",
  "mail": "must be a well-formed email address",
  "floor": "floor cannot be null"
}

实际查询和路径参数约束:

{
  "control.mark": "must be less than or equal to 5",
  "control.infect": "must be greater than 0",
  "control.age": "must be greater than or equal to 5"
}

下面是一个集成测试,以更好地理解link
依赖关系:

  • spring boot版本2.7.2
  • spring boot starter webflux
  • spring boot启动器验证
db2dz4w8

db2dz4w81#

您需要使用一个统一的ConstraintViolationException异常,并将所有约束收集到一个组中。
这可以通过@Validated(Group.class)注解实现。验证组文档。

1.为验证组创建界面

public interface Group {
}

2.为您的RestController申请组

@RestController
@Validated
@Slf4j
public class BookController {

    @PostMapping(value = "/control/{age}/mark/{mark}")
    @Validated(Group.class)
    public Object control(
            @PathVariable("age")
            @Min(value = 5, groups = Group.class) Integer age,

            @PathVariable("mark")
            @Max(value = 5, groups = Group.class) Integer mark,

            @Min(value = 3, groups = Group.class) @RequestParam(name = "conclusion") Integer conclusion,

            @Positive(groups = Group.class) @RequestParam(name = "infect") Integer infect,

            @Valid
            @RequestBody Book book
    ) {

      return new Book();
    }
}

3.为您的转移对象应用组

@Data
public class Book {

    @NotBlank(groups = Group.class)
    private String address;

    @NotNull(message = "floor cannot be null", groups = Group.class)
    private String floor;

    @Email(groups = Group.class)
    private String mail;
}

输出:

{
  "control.mark": "must be less than or equal to 5",
  "control.book.mail": "must be a well-formed email address",
  "control.infect": "must be greater than 0",
  "control.book.floor": "floor cannot be null",
  "control.book.address": "must not be blank",
  "control.age": "must be greater than or equal to 5"
}

相关问题