优雅的进行全局参数验证拦截0x01:pom.xml引入依

参数验证如果没有做全局验证,就会导致代码非常臃肿。存在大量的 if 判断非空语句。今天介绍一种优雅的方案。先介绍一个待会用到的注解@InitBinder,它的作用:

从字面上可以看出 @InitBinder 的作用是给 Binder 做初始化的,被此注解的方法可以对 WebDataBinder 初始化。WebDataBinder 是用于表单到方法的数据绑定的。

@InitBinder 只在 @Controller 中注解方法来为这个控制器注册一个绑定器初始化方法,方法只对本控制器有效。

@InitBinder
public void initBinder(WebDataBinder webDataBinder){
//TODO

}

0x01:pom.xml 引入依赖库

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.olive</groupId>
    <artifactId>valid-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath /> 
    </parent>
    <name>valid-demo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
    </dependencies>
</project>
复制代码

虽然是引用 @InitBinder 注解,但是底层框架还是使用 SpringBoot 的验证框架

#0x02:定义 Vo 对象

先定义一个 BaseVo 类,方便进行全局参数判断。这个类很简单,代码如下

package com.olive.vo;

import java.io.Serializable;

public class BaseVo implements Serializable{

}
复制代码

定义查询参数类 UserQueryVo,继承 BaseVo

package com.olive.vo;

import javax.validation.constraints.NotEmpty;

public class UserQueryVo extends BaseVo {

    @NotEmpty(message="不能为空")
    private String query;

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

}
复制代码

关键就是在字段里使用注解,标识参数不能为空

0x03:定义控制器

package com.olive.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.olive.vo.UserQueryVo;

@RestController
public class UserController {

    @RequestMapping("/user/queryUser")
    public Map queryUser(@RequestBody @Validated UserQueryVo queryVo){
        Map result = new HashMap();
        result.put("code", 200);
        result.put("msg", "success");
        return result;
    }

}
复制代码

在参数里使用 @Validated 注解,对 Vo 类进行校验标识。其实,正常做到这一步就可以完全进行参数校验了,但是没有一个统一拦截的入口。

0x04:添加参数校验统一拦截入口

package com.olive;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.olive.vo.BaseVo;

@RestControllerAdvice
public class UserControllerAdvice {

    @Autowired
    private Validator validator;

    @InitBinder
    public void initValid(WebDataBinder webDataBinder){
        Object target= webDataBinder.getTarget();
        if(target==null){
            return;
        }
        if(target instanceof BaseVo){
            BeanPropertyBindingResult result = new BeanPropertyBindingResult(target, target.getClass().getSimpleName());
            validator.validate(target, result);
            List<ObjectError> errors  = result.getAllErrors();
            if(errors==null || errors.isEmpty()){
                return;
            }
            throw new RuntimeException("参数错误");
        }
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map defaultErrorHandler(HttpServletRequest req, Exception e)  {
        Map result = new HashMap();
        result.put("code", 500);
        result.put("msg", e.getMessage());
        return result;
    }

}
复制代码

该段代码分析如下

  • 使用 @RestControllerAdvice 进行标识,该注解可以对标注了 @RestController 的控制器进行拦截

  • 在 initValid 方法中,使用 @InitBinder标识;同时该方法传入 WebDataBinder 对象,在方法里编写参数校验代码。如果验证不过直接抛出异常。这里抛出运行时异常 RuntimeException;实际项目中可以自定义继承 RuntimeException 的参数异常类ParamValidExecpiton

  • 在方法 defaultErrorHandler 中, 使用 @ExceptionHandler 标识;进行全局异常处理,这里直接拦截Exception;实际项目中可以直接拦截自己定义的参数异常类ParamValidExecpiton。

0x05:编写引导类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application 
{
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    }
}
复制代码

启动并进行验证

mmbiz.qpic.cn/mmbiz_png/g…

调试模式可以看到

image.png

这样就达到了统一控制参数校验,不需要分散到不同的代码块中了。