[英]How to group request javax validations?
我測試了 spring-boot-starter-validation 行為並注意到:首先驗證請求正文並拋出 WebExchangeBindException,然后驗證請求路徑和查詢參數並拋出 ConstraintViolationException。 那么,如何將這兩組約束加入到單個響應體中捕獲的單個異常中?
預期響應正文:
{
"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"
}
這是一個集成測試,可以更好地理解鏈接
依賴項:
您需要使用一個統一的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.為您的轉賬申請組object
@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;
}
Output:
{
"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"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.