-
Notifications
You must be signed in to change notification settings - Fork 17
ParamsValidation 数据校验
Timely Rain edited this page Apr 23, 2020
·
2 revisions
MornBoot提供参数自动校验功能,事实上Spring对参数校验的支持已经非常完善了,而MornBoot不仅支持SpringValidation所有的校验方式,同时完成了对校验结果的自动处理。
Since:v1.2.0
application.properties
#开启异常处理(默认)
morn.exception.enabled=true
#开启异常解释器
morn.exception-interpreter.enabled=true
#开启参数校验异常解释器
morn.exception-interpreter.validate.enabled=true
Maven
<!--支持更多校验异常-->
<dependency>
<groupId>site.morn.boot</groupId>
<artifactId>morn-boot-interpreter</artifactId>
<version>${morn.version}</version>
</dependency>
Entity - 使用注解约束实体类属性
- 支持javax.validation注解
- 支持hibernate.validator注解
@NotNull(groups = {Add.class, Update.class, Login.class})
@Size(min = 4, max = 32)
private String username;
@NotNull(groups = {Add.class, Login.class})
@Size(min = 4, max = 64)
private String password;
Controller - 使用Validated注解校验参,MornBoot内置一些校验组,用于区分不同业务场景
- Add
- Delete
- Login
- Operate
- Patch
- Put
- Query
- Search
- Update
@PostMapping("/login")
public Object login(@Validated(Login.class) User user) {
return RestBuilders.successMessage(); // 校验失败时,此处代码不会执行
}
发送请求:
curl -X POST \
http://localhost:8080/login \
-d password=123
输出结果:
输出内容支持国际化,属性的国际化将在后续版本中支持
user.password个数必须在4和32之间,user.username不能为null
密码个数必须在4和32之间,用户名不能为null [expect]