【Spring Boot】3.2 Validation 数据验证的使用

Spring Boot 数据验证实战
本文介绍了在Spring Boot中使用Validation进行数据验证的步骤,包括引入启动器、创建异常处理配置类,以及在Controller层的调用示例。通过BindingResult对象收集并处理验证结果。

这篇文章应该在Retrofit 和 VerifyImageCode 之前

Validation 是用来验证前端用户输入数据合法性的组建,使用步骤如下

引入启动器

        <!-- 数据验证支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

创建一个配置类 定义异常快速返回

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * Validation 校验错误 快速返回 配置文件
 */

@Configuration
public class ValidatorConfiguration {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}

创建一个异常统一处理的配置类

import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/***
 * Author: YL.Lou
 * Class: configs
 * Project: washes_base_backstage
 * Introduce: 统一异常处理接口
 * DateTime: 2022-06-29 16:28
 ***/

@RestControllerAdvice
public class ExceptionHandlerConfig {

    @Autowired
    private Result result;

    /**
     * validation参数校验异常 统一处理
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result exceptionHandler500(BindException e){
        // e.printStackTrace();
        StringBuilder stringBuilder = new StringBuilder();
        for (ObjectError error : e.getAllErrors()) {
            // stringBuilder.append(((FieldError) error).getField());
            stringBuilder.append(error.getDefaultMessage());
        }
        return result.failed(10003,stringBuilder.toString(), null);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Result exceptionHandler500(ConstraintViolationException e){
        // e.printStackTrace();
        StringBuilder stringBuilder = new StringBuilder();
        for (ConstraintViolation<?> error : e.getConstraintViolations()) {
            PathImpl pathImpl = (PathImpl) error.getPropertyPath();
            // String paramName = pathImpl.getLeafNode().getName();
            // stringBuilder.append(paramName);
            stringBuilder.append(error.getMessage());
        }
        return result.failed(10002,stringBuilder.toString(), null);
    }

    /**
     * 未知异常 统一处理
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        // e.printStackTrace();
        return result.failed(10001,e.getMessage(), null);
    }
}

在Controller层的调用示例

    /**
     * 获取手机验证码
     * @param uPhone 手机号
     * @param imgCode 图片验证码
     * @param imgKey 验证码图片Key值
     * @return
     */
    @PostMapping(value = "/smsCode")
    public Result getSmsCode(
            @NotBlank(message = "手机号码不能为空") @Pattern(regexp = "^\\d{11}$", message = "手机号码应为11位数字") @RequestParam("uPhone") String uPhone,
            @NotBlank(message = "图片验证码不能为空") @Pattern(regexp = "^\\d{4}$", message = "图片验证码应为4位数字") @RequestParam("imgCode") String imgCode,
            @NotBlank(message = "前端未传回Key值") @RequestParam("imgKey") String imgKey
    ){
        // 验证图片验证码是否正确
        if (verifyCodeImageUtil.checkImgCode(imgCode, imgKey)){
            return result.failed("图片验证码输入错误");
        }

        //调起service 获得短信发送的最终状态
        return publicService.getSmsCode(uPhone);
    }

另外一种调用和处理的方式(不依赖统一异常返回)

@PostMapping("save")
public void v1(@RequestBody @Valid AppUser appUser,BindingResult result){
      if(result.hasErrors()){
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
            }
        }
}

上述例子的重点在于 在验证的字段之后,紧跟着 BindingResult 对象,这个对象是用来收集验证结果的,并将验证结果传入方法体中。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值