SpringBoot自定义参数验证器

前要

之前我们介绍了JSR-303验证方式,十分的方便Spring都帮我们封装好了,但是对一些复杂的验证,还是需要更加灵活的验证器的。
JSR-303验证器传送门:https://www.jianshu.com/p/6980266af68e
自定义验证器是基于WebDataBinder,在请求流程中处理可以注册转换器之外,它还可以注册验证器!

请求参数实体类

StudentModel.java

package com.wzq.test.model;

import lombok.Data;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: Wzq
 * @create: 2020-01-19 11:27
 */
@Data
public class StudentModel {

    private String name;

}

转换器

package com.wzq.test.valid;

import com.wzq.config.exception.GlobalException;
import com.wzq.test.model.StudentModel;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @description: 学生验证器
 * @author: Wzq
 * @create: 2020-01-19 11:46
 */

public class StudentVaild implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(StudentModel.class);
    }

    @Override
    public void validate(Object o, Errors errors) {
        StudentModel studentModel = (StudentModel) o;
        if(studentModel==null){
            throw new GlobalException("学生为空!");
        }
        if(studentModel.getName()==null || studentModel.getName().isEmpty()){
            throw new GlobalException("学生名称不能为空!");
        }
    }
}

Controller调用

controller代码

package com.wzq.test.action;

import com.wzq.test.model.StudentModel;
import com.wzq.test.model.UserModel;
import com.wzq.test.valid.StudentVaild;
import com.wzq.utils.BatchDownFilesUtils;
import lombok.extern.java.Log;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

/**
 * @description: 测试Controller
 * @author: Wzq
 * @create: 2019-11-25 10:19
 */
@Controller
@RequestMapping(value = "test")
@Log
public class TestController {


     /**
     * 每次请求都会执行这个方法,添加验证器,如果在Controller中生效本Controller,想要全局生效,
     * 在@RestControllerAdvice中添加
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.addValidators(new StudentVaild());
    }



    @GetMapping("testStudent")
    @ResponseBody
    public Object testStudent(@Valid StudentModel studentModel){
        return studentModel;
    }
}

自定义异常类

package com.wzq.config.exception;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @description: 自定义一个全局异常
 * @author: Wzq
 * @create: 2019-12-26 13:04
 */
@Data
@ToString
public class GlobalException extends RuntimeException  {


    private Integer code = -1;

    private String errMsg;

    public GlobalException(String message) {
        super(message);
        this.errMsg = message;
    }
}

全局捕获异常类配置

GlobalExceptionAdvice.java

package com.wzq.config.exception;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description: 全局异常处理类
 * @author: Wzq
 * @create: 2019-12-26 11:01
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {


    /**
     * 每次请求都会执行这个方法,添加验证器 全局添加
     * @param webDataBinder
     */
//    @InitBinder
//    public void initBinder(WebDataBinder webDataBinder){
//        webDataBinder.addValidators(new StudentVaild());
//    }

    /**
     * 指定拦截异常的类型
     *
     * @param e
     * @return json格式类型
     */
    @ExceptionHandler({Exception.class}) //指定拦截异常的类型
    public Object customExceptionHandler(Exception e) {
        //打印异常日志
        e.printStackTrace();
        if(e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            return globalException.getErrMsg();
        }
        return "系统异常";
    }
}

成功

image.png

image.png

个人微信公众,经常更新一些实用的干货:
image.png

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值