前要

之前我们介绍了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. python 读取 写入txt文件

    filename = 'pi_digits.txt' with open(filename) as f:#默认以只读方式打开文件 lines = f.readlines()#读取所有行,结果为列表,每 ...

  2. ES6新增语法(三)——面向对象

    ES6中json的2个变化 简写:名字和值相同时,json可以可以简写 let a=12,b=5; let json = { a, b } console.log(json) // { a:12 , ...

  3. vulnhub-DC:1靶机渗透记录

    准备工作 在vulnhub官网下载DC:1靶机https://www.vulnhub.com/entry/dc-1,292/ 导入到vmware 打开kali准备进行渗透(ip:192.168.200 ...

  4. webSocket实现多人聊天功能

    webSocket实现多人在线聊天 主要思路如下: 1.使用vue构建简单的聊天室界面 2.基于nodeJs 的webSocket开启一个socket后台服务,前端使用H5的webSocket来创建一 ...

  5. 一文彻底弄懂cookie、session、token

    前言 作为一个JAVA开发,之前有好几次出去面试,面试官都问我,JAVAWeb掌握的怎么样,我当时就不知道怎么回答,Web,日常开发中用的是什么?今天我们来说说JAVAWeb最应该掌握的三个内容. 发 ...

  6. Jmeter RMI 反序列化命令执行漏洞(CVE-2018-1297)

    下载ysoserial,git git clone https://github.com/frohoff/ysoserial.git cd ysoserialmvn clean package -Ds ...

  7. GhostScript 沙箱绕过(命令执行)漏洞(CVE-2018-16509)

    影响范围: Ghostscript 9.24之前版本 poc地址 https://github.com/vulhub/vulhub/blob/master/ghostscript/CVE-2018-1 ...

  8. homeless靶机

    仅供个人娱乐 靶机信息 下载地址:https://www.vulnhub.com/entry/homeless-1,215/ 一.主机扫描 二.信息收集 在网页源码和页面上,我们发现User-Agen ...

  9. 关于win7+cenos 7双系统安装

    ---恢复内容开始--- 1,cenos 0 7制作U盘启动 制作工具 http://pan.baidu.com/s/1nv9lpmp 镜像自备 2,安装centos 7 释放磁盘空间,如:20G.用 ...

  10. 等Excel工作簿关闭后自动加密压缩备份2019年10月9日.ahk

    ;; 等Excel工作簿关闭后自动加密压缩备份2019年10月9日.ahk;; 腾讯QQ号 595076941; 作者:徐晓亮(weiyunwps618); 写作日期:2019年5月15日; 版本号: ...