Spring Boot 使用@Validated校验参数

背景说明:

后端开发中,参数校验是必不可少的一个环节;写起来比较繁琐,这里就用@Validated来处理参数校验.这里以获取验证码接口为例

1.使用Maven创建一个Spring Boot项目

Spring Boot项目HelloWord

2.在.pom文件中引入相关依赖:

 <!--  参数校验-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        

3.定义一个对象


/**
 * 请求获取验证码
 */
public class RequestVerificationCode {
    //进行非空判断
    @NotEmpty(message = "国际区号不能为空")
    public String countrycode;  //用户手机号码国家码


    //进行非空判断
    //添加正则表达式校验
    @NotEmpty(message = "手机号码不能为空")
    @Pattern(regexp = "^[1][3,4,5,7,8,9][0-9]{9}$", message = "手机号码不合法")
    public String mobile;  //用户手机号码

    public String getCountrycode() {
        return countrycode;
    }

    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

}

4.Controller类中编写接口

  /**
     * 请求获取验证码
     *POST方法中接收刚才我们写的RequestVerificationCode,使用@Validated类
     * @param req
     * @return
     */
    @RequestMapping(value = "requestVerificationCode", method = RequestMethod.POST)
    public BaseResponse requestVerificationCode(@RequestBody @Validated RequestVerificationCode req) {
        return userServices.requestVerificationCode(req);
    }

5.当参数校验失败时会抛出异常MethodArgumentNotValidException

6.统一处理异常,增加异常处理的类


@ControllerAdvice
public class ExceptionHandle {

    /**
     * 捕获参数异常
     *
     * @param exception MethodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResponse argumentException(MethodArgumentNotValidException exception) {
        String resut = "";
        //查看MethodArgumentNotValidException类可以发现,异常的信息在BindingResult下List<ObjectError>中
        //我这里取第一条的信息进行展示,可根据实际项目情况自行修改
        //getDefaultMessage()获取的信息就是我们RequestVerificationCode中的message部分
        if (exception.getBindingResult() != null
                && exception.getBindingResult().getAllErrors() != null
                && exception.getBindingResult().getAllErrors().size() > 0) {
            resut = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        //自定义的返回类,可根据实际项目情况自行修改
        BaseResponse response = new BaseResponse();
        response.setRsbCode(RsbCode.Rsb_Error_RequestJson, resut);
        return response;
    }


    /**
     * 全局捕获异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse handle(Exception e) {
        BaseResponse response = new BaseResponse();
        response.setRsbCode(RsbCode.Rsb_SYS_ERR, e.getMessage());
        return response;
    }


}


7.GET请求时校验参数

注意:

  • 首先将@Validated注解加载Controller上
  • 校验失败时返回的异常为ConstraintViolationException
//
//


   /**
     * 请求获取验证码
     *
     * @param countrycode
     * @param mobile
     * @return
     */
    @GetMapping(value = "requestVerificationCode")
    public BaseResponse requestVerificationCode(
            @NotEmpty(message = "国际区号不能为空")
            @RequestParam String countrycode,
            @NotEmpty(message = "手机号码不能为空")
            @Pattern(regexp = "^[1][3,4,5,7,8,9][0-9]{9}$", message = "手机号码不合法")
            @RequestParam String mobile) {
        return userServices.requestVerificationCode(countrycode, mobile);
    }
    

8.运行项目,进行测试

测试请求的数据

{
  "countrycode": "",
  "mobile": "13333333333"
}

响应数据

{
  "resb": 400,
  "resbInfo": "国际区号不能为空"
}

请求数据

{
  "countrycode": "86",
  "mobile": "123456789"
}

返回数据

{
  "resb": 400,
  "resbInfo": "手机号码不合法"
}

附录注解说明:

@Null                           被注释的元素必须为 null    
@NotNull                        被注释的元素必须不为 null    
@AssertTrue                     被注释的元素必须为 true    
@AssertFalse                    被注释的元素必须为 false    
@Min(value)                     被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)                     被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@DecimalMin(value)              被注释的元素必须是一个数字,其值必须大于等于指定的最小值    
@DecimalMax(value)              被注释的元素必须是一个数字,其值必须小于等于指定的最大值    
@Size(max=, min=)               被注释的元素的大小必须在指定的范围内    
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内    
@Past                           被注释的元素必须是一个过去的日期    
@Future                         被注释的元素必须是一个将来的日期    
@Pattern(regex=,flag=)           被注释的元素必须符合指定的正则表达式    


Hibernate Validator提供的校验注解:  
@NotBlank(message =)            验证字符串非null,且trim后长度必须大于0    
@Email                          被注释的元素必须是电子邮箱地址    
@Length(min=,max=)              被注释的字符串的大小必须在指定的范围内    
@NotEmpty                       被注释的字符串的必须非空    
@Range(min=,max=,message=)      被注释的元素必须在合适的范围内

@AssertFalse                    校验false  
@AssertTrue                     校验true  
@DecimalMax(value=,inclusive=)  小于等于value,  
inclusive=true,是小于等于  
@DecimalMin(value=,inclusive=)  与上类似  
@Max(value=)                    小于等于value  
@Min(value=)                    大于等于value  
@NotNull                        检查Null  
@Past                           检查日期  
@Pattern(regex=,flag=)           正则  
@Size(min=, max=)               字符串,集合,map限制大小  
@Valid                          对po实体类进行校验
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值