前要

之前我们介绍了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 "系统异常";
}
}

成功

SpringBoot自定义参数验证器的更多相关文章

  1. SpringBoot自定义参数解析器

    一.背景 平常经常用 @RequestParam注解来获取参数,然后想到我能不能写个自己注解获取请求的ip地址呢?就像这样 @IP String ip 二.分析 于是开始分析 @RequestPara ...

  2. SpringBoot系列教程web篇之如何自定义参数解析器

    title: 190831-SpringBoot系列教程web篇之如何自定义参数解析器 banner: /spring-blog/imgs/190831/logo.jpg tags: 请求参数 cat ...

  3. SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用

    1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...

  4. 自研后端HTTP请求参数验证器服务ParamertValidateService

    好处:方便了后端对HTTP请求中参数进行核验,只需一次编写效验器,一行代码便可对所有参数的pojo进行参数核验!而且更改效验逻辑时只需要更改效验器类即可,实现了解耦合. 只需要程序员按照规范开发一个P ...

  5. springmvc 源码分析(三) -- 自定义处理器映射器和自定义处理器适配器,以及自定义参数解析器 和错误跳转自定页面

    测试环境搭建: 本次搭建是基于springboot来实现的,代码在码云的链接:https://gitee.com/yangxioahui/thymeleaf.git DispatcherServlet ...

  6. 实现一个可配置的java web 参数验证器

    当使用java web的servlet来做接口的时候,如果严格一点,经常会对请求参数做一些验证并返回错误码.我发现通常参数验证的代码就在servlet里边,如果参数不正确就返回相应的错误码.如果接口数 ...

  7. SpringMVC 自定义参数解析器.

    一.简述 有没有想过像 @RequestParam.@RequestBody 这些注解的工作原理呢?为什么 form 表单.application/json 的参数能够直接封装进 Bean 对象中呢? ...

  8. Spring自定义参数解析器

    结合redis编写User自定义参数解析器UserArgumentResolver import javax.servlet.http.Cookie; import javax.servlet.htt ...

  9. SpringMVC自动封装List对象 —— 自定义参数解析器

    前台传递的参数为集合对象时,后台Controller希望用一个List集合接收数据. 原生SpringMVC是不支持,Controller参数定义为List类型时,接收参数会报如下错误: org.sp ...

随机推荐

  1. ESP32-FAT文件系统使用磨损均衡存储文件笔记

    基于ESP-IDF4.1 1 /* 2 FAT文件系统存储文件,使用磨损均衡库wear-leveling 3 */ 4 5 #include <stdlib.h> 6 #include & ...

  2. Python单元测试框架unittest之断言(assert)

    unittest中断言主要有三种类型: 1.基本的布尔断言,即:要么正确,要么错误的验证 2.比较断言,如比较两个变量的值(跟上面的布尔断言区别不大,主要是通过比较两个变量的值得出布尔值) 3.复杂断 ...

  3. passwd 简单记录

    passwd [选项] 登录名 -e,--expire 强制用户密码过期 这时候需要使用root账户给tel用户重新设置密码 -l,--lock 锁定指定用户密码 -u, --unlock 给指定账户 ...

  4. Java基础00-第一个程序2

    1. 常用DOS命令 1.1 打开命令提示窗口 按下win+R 输入cmd 按下回车键 得到命令提示窗口 1.2 常用命令 2. Path环境变量的配置 2.1 为什么要配置Path环境变量 2.2 ...

  5. java网络编程基础——TCP网络编程三

    AIO实现非阻塞通信 java7 NIO2 提供了异步Channel支持,这种异步Channel可以提供更高效的IO,这种基于异步Channel的IO被称为异步IO(Asynchronous IO) ...

  6. 【剑指offer】28. 对称的二叉树

    剑指 Offer 28. 对称的二叉树 知识点:二叉树:递归 题目描述 请实现一个函数,用来判断一棵二叉树是不是对称的.如果一棵二叉树和它的镜像一样,那么它是对称的. 示例 输入:root = [1, ...

  7. 看懂UML类图笔记

    在学习设计模式的时候,经常会遇到UML类图,所以就找了一些资料,做一些笔记. 从一个示例开始 下面这个类图,类之间的关系是我们需要关注的: 车的类图结构为<<abstract>> ...

  8. kafka单机环境配置以及基本操作

    安装地址(已亲测有效):https://www.linuxidc.com/Linux/2019-03/157650.htm

  9. windows系统pycharm终端更改为git bash

    引自:https://blog.csdn.net/u011519550/article/details/89855122 设置路径:file--setting--tools--terminal--ap ...

  10. (6java)计算机语言发展史

    (6java)计算机语言发展史 机器语言: 程序是0和1的组合,比如:0000.0001.1100110 汇编语言: 程序比机器语言好理解一点点 高级语言: 比较适合老美,苦了英语差的孩子们了,哈哈. ...