SpringBoot如何进行全局参数验证拦截呢?
下文笔者讲述SpringBoot对全局参数验证拦截的方法及示例分享,如下所示
参数验证: 是所有程序都绕不开的话题,也是每一个方法必备的功能 那么如何采用一种统一的方式处理参数验证呢? 下文笔者将一一道来,如下所示
优雅验证全局参数的方法
实现思路: 1.借助@InitBinder注解(放在需验证的controller方法上),实现参数的获取 2.使用拦截器(@RestControllerAdvice)对参数的数据类型进行验证 如: @InitBinder public void initBinder(WebDataBinder webDataBinder){ //TODO }例:
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.java265</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>
定义VO对象
package com.java265.vo; import java.io.Serializable; public class BaseVo implements Serializable{ } package com.java265.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; } }
定义控制器
package com.java265.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.java265.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; } }
添加参数校验统一拦截入口
package com.java265; 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.java265.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注解的功能
@RestControllerAdvice注解的功能: 对@RestController控制器拦截 initValid方法中 使用@InitBinder标识 该方法传入WebDataBinder对象 此时方法中写入参数校验代码 当验证不通过时, 直接抛出异常 抛出运行时异常RuntimeException
启动SpringBoot
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); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。