spring boot 参数校验(基于 hibernate validator)
1. 简介与依赖
- 作用:对 controller 接收的参数进行合法性校验,提升接口健壮性。
- 底层实现:hibernate validator(bean validation 规范的参考实现)。
- 推荐依赖
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-validation</artifactid>
</dependency>自动引入 hibernate-validator + javax.validation-api,无需手动管理版本。
2. 使用方式
校验 @requestbody(json 对象)
- 在参数前加
@valid,无需@validated。
@postmapping("/user")
public result createuser(@valid @requestbody user user) { ... }
校验 @requestparam / @pathvariable 等
- 必须在 controller 类(或方法)上加
@validated。
@restcontroller
@validated // ← 关键!
public class usercontroller {
@getmapping("/user/{id}")
public result getuser(@min(1) @pathvariable long id) { ... }
}
最佳实践:controller 类统一加 @validated,覆盖所有校验场景。
3. 常用注解
非空校验
- @notnull:验证对象不为null,但允许空字符串或空白字符
- @notempty:验证字符串/集合/数组非null且长度/大小>0(不检查空白字符)
- @notblank:验证字符串非null且至少包含一个非空白字符
范围校验
- @size(min=, max=):限制字符串/集合/数组的长度/大小范围
- @min:验证数字最小值(含边界值)
- @max:验证数字最大值(含边界值)
格式校验
- @email:验证字符串是否符合邮箱格式
- @pattern(regexp = “…”):通过正则表达式自定义校验规则
时间校验
- @past:验证日期是否在当前时间之前
- @future:验证日期是否在当前时间之后
4. 全局异常处理器
统一处理校验失败异常,返回结构化错误信息。有了全局异常处理器,前端可以收到规范化的错误信息
@restcontrolleradvice
public class globalvalidationexceptionhandler {
// 处理 @requestbody 校验失败
@exceptionhandler(methodargumentnotvalidexception.class)
@responsestatus(httpstatus.bad_request)
public apiresult<map<string, string>> handlerequestbody(
methodargumentnotvalidexception ex) {
map<string, string> errors = new hashmap<>();
ex.getbindingresult().getfielderrors()
.foreach(e -> errors.put(e.getfield(), e.getdefaultmessage()));
return apiresult.error(400, "参数校验失败").data(errors);
}
// 处理 @requestparam / @pathvariable 校验失败
@exceptionhandler(constraintviolationexception.class)
@responsestatus(httpstatus.bad_request)
public apiresult<map<string, string>> handleparams(
constraintviolationexception ex) {
map<string, string> errors = new hashmap<>();
ex.getconstraintviolations().foreach(v ->
errors.put(v.getpropertypath().tostring(), v.getmessage()));
return apiresult.error(400, "参数校验失败").data(errors);
}
}
返回示例:
{ "code": 400, "message": "参数校验失败", "data": { "name": "姓名不能为空" } }
到此这篇关于springboot校验前端传递的参数的流程步骤的文章就介绍到这了,更多相关springboot校验前端传递参数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论