springboot笔记--数据校验的使用

数据校验

在低版本的springboot中用的是hibernate validation

要导入对应hibernate依赖

但在高版本的springboot中,已经加入了validation的坐标

直接使用

<!-- hibernate 验证框架 -->
    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
   </dependency>

使用方法:

1.在要使用的类属性上加入对应的注解

public class RegistLoginBO {

    @NotBlank(message = "手机号不能为空")
    @Length(min = 11, max = 11, message = "手机长度不正确")
    private String mobile;
    @NotBlank(message = "验证码不能为空")
    private String smsCode;

}

2.在controller层中使用@Valid注解对要接收的对象进行验证,如果验证中有错误,会放在一个BindingResult 中,但是这样写对代码具有侵入性。

(1)

 @PostMapping("login")
    public GraceJSONResult login(@Valid @RequestBody RegistLoginBO registLoginBO,
//                                 BindingResult result,    // 对代码有侵入性
                                 HttpServletRequest request) throws Exception {

        // 0. 判断BindingResult中是否保存了错误的验证信息,如果有,则需要返回到前端
//        if( result.hasErrors() ) {
//            Map<String, String> map = getErrors(result);
//            return GraceJSONResult.errorMap(map);
//        }

    }

 public Map<String, String> getErrors(BindingResult result) {
      Map<String, String> map = new HashMap<>();
      List<FieldError> errorList = result.getFieldErrors();
       for (FieldError ff : errorList) {
         // 错误所对应的属性字段名
           String field = ff.getField();
           // 错误的信息
           String msg = ff.getDefaultMessage();
           map.put(field, msg);
       }
        return map;
    }

(2)使用自定义异常处理解决侵入性,且解耦

MethodArgumentNotValidException.class 这是数据校验失败抛出的异常类

交给自定义异常处理返回给controller

 @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMethodArgumentNotValid(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> map = getErrors(result);
        return GraceJSONResult.errorMap(map);
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值