[英]springboot, how to valid @RequestBody
current code当前代码
@Slf4j
@RestController
public class TestController {
@Validated
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
String test( @RequestBody @NotEmpty @Valid List<@NotBlank @Valid UUID> uuids) {
return uuids.toString();
}
}
problem问题
--header 'Content-Type: application/json' \
--data-raw '[]'
curl --location --request PUT 'localhost:8080' \
--header 'Content-Type: application/json' \
--data-raw '[""]'
valid passes.有效通行证。 But i don't want it
但我不想要
I want to validate the curl request in the sample above.我想验证上面示例中的 curl 请求。 Is there any way to do it without dto?
没有dto有什么办法吗?
The correct way of doing it正确的做法
@Slf4j
@RestController
@Validated
public class TestController {
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
String test( @RequestBody @NotEmpty @Valid List<@NotNull @Valid UUID>
uuids) {
return uuids.toString();
}
}
we have to annotate the beans, which shall be validated, with @Validated.我们必须用@Validated 注释要验证的bean。 Also for UUID @NotNull will suffice the requirement as No validator exists for this constraint for object UUID
对于 UUID,@NotNull 也可以满足要求,因为 object UUID 的此约束不存在验证器
Validation Messages can also be customised by providing "message" param for @NotEmpty and @NotNull.验证消息也可以通过为@NotEmpty 和@NotNull 提供“消息”参数来定制。 like @NotEmpty(message = "cannot be empty")
比如@NotEmpty(message = "不能为空")
If any of the validations fail, ConstraintViolationException is thrown.如果任何验证失败,则会引发 ConstraintViolationException。 Exception handling can be done to customise this exception and throw 400 Bad Request.
可以做异常处理来自定义这个异常并抛出 400 Bad Request。
Add a comment on the field在字段上添加评论
@Getter
@Setter
public class Person {
@NotNull(message = "[id] cannot be empty")
private Long id;
@NotBlank(message = "[name] cannot be blank")
private String name;
@NotBlank(message = "[email] cannot be blank")
private String email;
@NotBlank(message = "[birthday] cannot be blank")
private Date birthday;
@Override
public String toString() {
return JSONUtils.toJSONString(this);
}
}
Use @Validated for validation使用@Validated进行验证
@RestController
@RequestMapping
public class TestController {
@PostMapping(value = "/get")
public String get(@Validated @RequestBody Person person) {
return person.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.