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 "系统异常";
}
}
成功


SpringBoot自定义参数验证器的更多相关文章
- SpringBoot自定义参数解析器
一.背景 平常经常用 @RequestParam注解来获取参数,然后想到我能不能写个自己注解获取请求的ip地址呢?就像这样 @IP String ip 二.分析 于是开始分析 @RequestPara ...
- SpringBoot系列教程web篇之如何自定义参数解析器
title: 190831-SpringBoot系列教程web篇之如何自定义参数解析器 banner: /spring-blog/imgs/190831/logo.jpg tags: 请求参数 cat ...
- SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用
1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...
- 自研后端HTTP请求参数验证器服务ParamertValidateService
好处:方便了后端对HTTP请求中参数进行核验,只需一次编写效验器,一行代码便可对所有参数的pojo进行参数核验!而且更改效验逻辑时只需要更改效验器类即可,实现了解耦合. 只需要程序员按照规范开发一个P ...
- springmvc 源码分析(三) -- 自定义处理器映射器和自定义处理器适配器,以及自定义参数解析器 和错误跳转自定页面
测试环境搭建: 本次搭建是基于springboot来实现的,代码在码云的链接:https://gitee.com/yangxioahui/thymeleaf.git DispatcherServlet ...
- 实现一个可配置的java web 参数验证器
当使用java web的servlet来做接口的时候,如果严格一点,经常会对请求参数做一些验证并返回错误码.我发现通常参数验证的代码就在servlet里边,如果参数不正确就返回相应的错误码.如果接口数 ...
- SpringMVC 自定义参数解析器.
一.简述 有没有想过像 @RequestParam.@RequestBody 这些注解的工作原理呢?为什么 form 表单.application/json 的参数能够直接封装进 Bean 对象中呢? ...
- Spring自定义参数解析器
结合redis编写User自定义参数解析器UserArgumentResolver import javax.servlet.http.Cookie; import javax.servlet.htt ...
- SpringMVC自动封装List对象 —— 自定义参数解析器
前台传递的参数为集合对象时,后台Controller希望用一个List集合接收数据. 原生SpringMVC是不支持,Controller参数定义为List类型时,接收参数会报如下错误: org.sp ...
随机推荐
- Spring学习总结(一)---谈谈对Spring IOC的理解(一:理论知识理解)
学习过Spring框架的人一定都会听过Spring的IoC(控制反转) .DI(依赖注入)这两个概念,对于初学Spring的人来说,总觉得IoC .DI这两个概念是模糊不清的,是很难理解的,今天和大家 ...
- Git submodule 拉取子模块
$ git clone https://code.Xcode.com.client.git Cloning into 'vipkid-pc-client'... Username for 'https ...
- AcWing 1086. 恨7不成妻(【代码简洁】标准记忆化搜索+超详解!!)
看到这题用循环写的dp代码瑟瑟发抖~ 数位dp一般记忆化搜索的写法思维难度较低,也比较常用,这题的简洁代码应该就可以显现出其优越性 (用时4ms,可能比用循环写的dp还要快) 那这里补充一下记忆化搜索 ...
- Pytest单元测试框架之parametrize参数化
1.参数化的本质:相同的步骤,但测试数据不同,比如登录的场景 import mathimport pytest# 方式一:分离出Listdef list_Test(): list = [ [2, 2, ...
- Java-数组有关
1.复制数组 复制数组主要有三类方法: 1.使用循环语句逐个赋值数组元素 2.使用System类中的静态方法arraycopy 3.使用clone方法复制数组 对于2,详述如下: arraycopy( ...
- R语言客户端RStudio快捷键大全
Console Description Windows & Linux Mac 将光标定位到控制台 Ctrl+2 Ctrl+2 清空控制台 Ctrl+L Command+L 将光标定位到行首 ...
- Mysql数据量较大时分页查询优化
据表 collect ( id, title ,info ,vtype) 就这4个字段,其中 title 用定长,info 用text, id 是主键,vtype是int,vtype是索引. 最后co ...
- Python自动化测试面试题-Linux篇
目录 Python自动化测试面试题-经验篇 Python自动化测试面试题-用例设计篇 Python自动化测试面试题-Linux篇 Python自动化测试面试题-MySQL篇 Python自动化测试面试 ...
- ifix 自动化(Automation)错误弹窗的解决方案
在先前ifix项目中添加了语音模块,然后概率性跳出自动化(Automation)错误弹窗,先前分析了很多种原因,从代码的冗余,编码等角度进行了优化,效果不是很理想,仍然会概率性出现.经过反反复复大约3 ...
- djinn靶机
仅供个人娱乐 靶机信息 https://download.vulnhub.com/djinn/djinn.ova 一.主机探测 二.漏洞的查找和利用 21端口ftp 匿名登录 7331端口 命令执行 ...