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 ...
随机推荐
- ctf杂项之easy_nbt
下载附件查看 除了几个文件之外,没有思路 搜索nbt可知,可以使用nbtexplorer工具 果断下载,然后打开题目下载的目录 crrl+f搜索flag 猜测kflag{Do_u_kN0w_nbt?} ...
- NTFS安全权限
一.NTFS权限概述 1.通过设置NTFS权限,实现不同的用户访问不同的对象的权限 2.分配了真确的访问权限后,用户才能访问其资源 3.设置权限防止资源被篡改.删除 二.文件系统概述 文件系统即在外部 ...
- SpringBoot | 2.1 SpringBoot自动装配原理
@ 目录 前言 1. 引入配置文件与配置绑定 @ImportResource @ConfigurationProperties 1.1 @ConfigurationProperties + @Enab ...
- shell脚本(2)-shell脚本语法
一.如何抒写shell脚本 1.shell脚本的命名 名字要有意义,不要以a.b.c.1.2.3这种方式命令,建议以sh结尾,在30个字节内,例如:check_memory.sh 2.shell脚本 ...
- final修饰符(5)-final方法
final修饰的类的方法不能被重写,例如如果父类不希望子类重写某个方法,则可以使用final修饰符修饰该方法 在java的Object类里面有一个final方法:getClass(),因为Java不希 ...
- 使用python对工作簿每个sheet表进行数据可视化展示(本案例是从第2个sheet开始循环读取也就是索引为1的表)
# 导入相关模块from pyecharts.charts import Barfrom pyecharts import options as optsfrom pyecharts.charts i ...
- C++:第一个c++程序
// C++ 环境搭建: https://www.bilibili.com/video/BV1nt4y1r7Ez?t=535 // 学习资料:https://www.runoob.com/cplusp ...
- ecshop二次开发笔记--订单表结构ecs_order_info说明
-- 表的结构 `ecs_order_info` CREATE TABLE IF NOT EXISTS `ecs_order_info` ( `order_id` mediumint(8) uns ...
- 医疗器械软件产品经理必读的法规及标准-YY/T0664(一)
医疗器械软件产品经理必读的法规及标准-YY/T0664(一) 医疗器械软件的产品经理,需要熟读医药行业标准,在软件设计开发的整个生存周期过程中,我们需要根据<YY/T 0664 医疗器械软件 软 ...
- windows使用nvm管理node不同版本
最近项目需要升级,新技术需要的node版本较高,而新node不兼容旧版本node,而原项目仍需要继续维护,所以就需要在本地有多个版本的node,基本原理是在环境配置中修改系统变量node的版本文件夹路 ...