前要

之前我们介绍了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-使用有刷直流电机笔记

    基于ESP-IDF4.1 1 /* 2 * 刷直流电动机控制示例,代码通过L298电机芯片测试 3 */ 4 5 #include <stdio.h> 6 7 #include " ...

  2. STM32中STD、HAL、LL库比较

    ST为开发者提供了标准外设库(STD库).HAL库.LL库 三种.前两者都是常用的库,后面的LL库是ST新添加的,随HAL源码包一起提供,目前支持的芯片也偏少. 标准外设库(Standard Peri ...

  3. python 07篇 内置函数和匿名函数

    一.内置函数 # 下面这些要掌握 # len type id print input open # round min max filter map zip exec eval print(all([ ...

  4. C语言:数组数据交换

    //交换数组中各个变量的值:第1和最后一个交换,第2与倒数第二个交换 #include <stdio.h> int main() { int a[]={1,2,3,4,5,6,7,8,9} ...

  5. python 函数定义自变量的写法及调用

    import pandas as pd #函数定义时指明自变量,指明自变量的类型,指定自变量的默认值 #函数定义时,可以通过"自变量名称=常量"的方式指定自变量的默认值,调用时可以 ...

  6. ELK多索引配置(filebeat)

     nginx日志收集: ​ ​ #-------------------------输入 filebeat.inputs: ​ #----------json日志---------- ​ - type ...

  7. 【剑指offer】50.数组中重复出现的数字

    50.数组中重复出现的数字 知识点:数组:Set的不可重复性 题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内. 数组中某些数字是重复的,但不知道有几个数字是重复的.也不知道每个数字重 ...

  8. Spring总结之SpringMvc上

    一.简介 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架. 二.流程架构 1.用户发送请求至 前端控制器DispatcherServlet ...

  9. PAT乙级:1090危险品装箱(25分)

    PAT乙级:1090危险品装箱(25分) 题干 集装箱运输货物时,我们必须特别小心,不能把不相容的货物装在一只箱子里.比如氧化剂绝对不能跟易燃液体同箱,否则很容易造成爆炸. 本题给定一张不相容物品的清 ...

  10. [HAOI2012]外星人 题解

    人类智慧题. 首先,只有 \(\varphi(1)=\varphi(2)=1\).再考虑题目中给的提示: \[\varphi\left(\prod_{i = 1}^m p_i^{q_i}\right) ...