SpringBoot 如何进行参数校验
为什么需要参数校验
在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数进行校验,例如登录的时候需要校验用户名和密码是否为空,添加用户的时候校验用户邮箱地址、手机号码格式是否正确。 靠代码对接口参数一个个校验的话就太繁琐了,代码可读性极差。
Validator
框架就是为了解决开发人员在开发的时候少写代码,提升开发效率;Validator专门用来进行接口参数校验,例如常见的必填校验,email格式校验,用户名必须位于6到12之间等等。
接下来我们看看在SpringbBoot中如何集成参数校验框架。
SpringBoot中集成参数校验
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定义参数实体类
package com.didiplus.modules.sys.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/25
* Desc: 字典类型领域模型
*/
@Data
@ApiModel(value = "字典类型")
public class SysDictType {
@ApiModelProperty("ID")
private String id;
@NotBlank(message = "字典名称必填项")
@ApiModelProperty(value = "字典名称",example = "用户ID")
private String typeName;
@NotBlank(message = "字典编码不能为空")
@ApiModelProperty(value = "字典编码")
private String typeCode;
@Email(message = "请填写正确的邮箱地址")
@ApiModelProperty(value = "字典编码")
private String email;
@ApiModelProperty(value = "字典描述")
private String description;
@NotBlank(message = "字典状态不能为空")
@ApiModelProperty(value = "字典状态")
private String enable;
}
常见的约束注解如下:
注解 | 功能 |
---|---|
@AssertFalse | 可以为null,如果不为null的话必须为false |
@AssertTrue | 可以为null,如果不为null的话必须为true |
@DecimalMax | 设置不能超过最大值 |
@DecimalMin | 设置不能超过最小值 |
@Digits | 设置必须是数字且数字整数的位数和小数的位数必须在指定范围内 |
@Future | 日期必须在当前日期的未来 |
@Past | 日期必须在当前日期的过去 |
@Max | 最大不得超过此最大值 |
@Min | 最大不得小于此最小值 |
@NotNull | 不能为null,可以是空 |
@Null | 必须为null |
@Pattern | 必须满足指定的正则表达式 |
@Size | 集合、数组、map等的size()值必须在指定范围内 |
必须是email格式 | |
@Length | 长度必须在指定范围内 |
@NotBlank | 字符串不能为null,字符串trim()后也不能等于"" |
@NotEmpty | 不能为null,集合、数组、map等size()不能为0;字符串trim()后可以等于"" |
@Range | 值必须在指定范围内 |
@URL | 必须是一个URL |
定义校验类进行测试
package com.didiplus.modules.sys.controller;
import com.didiplus.modules.sys.domain.SysDictType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/25
* Desc: 数据字典控制器
*/
@RestController
@Api(tags = "数据字典")
@RequestMapping("/api/sys/dictType")
public class SysDictTypeController {
@ApiOperation("字典添加")
@PostMapping("/add")
public SysDictType add(@Validated @RequestBody SysDictType sysDictType) {
return sysDictType;
}
@ApiOperation("字典修改")
@PutMapping("/edit")
public SysDictType edit(@Validated @RequestBody SysDictType sysDictType) {
return sysDictType;
}
}
这里我们先定义两个方法add
,edit
,都是使用了 @RequestBody
注解,用于接受前端发送的json
数据。
打开接口文档模拟提交数据
通过接口文档看到前三个字段都是必填项。
由于email的格式不对就被拦截了,提示是因为邮箱地址不对。
参数异常加入全局异常处理器
虽然我们之前定义了全局异常拦截器,也看到了拦截器确实生效了,但是 Validator
校验框架返回的错误提示太臃肿了,不便于阅读,为了方便前端提示,我们需要将其简化一下。
直接修改之前定义的 RestExceptionHandler
,单独拦截参数校验的三个异常:javax.validation.ConstraintViolationException
,org.springframework.validation.BindException
,org.springframework.web.bind.MethodArgumentNotValidException
,代码如下:
package com.didiplus.common.web.response.Handler;
import com.didiplus.common.web.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/24
* Desc: 默认全局异常处理。
*/
@RestControllerAdvice
public class RestExceptionHandler {
/**
* 默认全局异常处理。
* @param e the e
* @return ResultData
*/
@ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
public ResponseEntity<Result<String>> handleValidatedException(Exception e) {
Result<String> result = null;
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex =(MethodArgumentNotValidException) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"))
);
} else if (e instanceof ConstraintViolationException){
ConstraintViolationException ex = (ConstraintViolationException) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining(";"))
);
}else if (e instanceof BindException) {
BindException ex = (BindException ) e;
result = Result.failure(HttpStatus.BAD_REQUEST.value(),
ex.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"))
);
}
return new ResponseEntity<>(result,HttpStatus.BAD_REQUEST);
}
}
美化之后错误信息提示更加友好。
自定义参数校验
虽然Spring Validation 提供的注解基本上够用,但是面对复杂的定义,我们还是需要自己定义相关注解来实现自动校验。
比如上面实体类中添加的sex性别属性,只允许前端传递传 M,F 这2个枚举值,如何实现呢?
创建自定义注解
package com.didiplus.common.annotation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/26
* Desc:
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Repeatable(EnumString.List.class)
@Documented
@Constraint(validatedBy = EnumStringValidator.class)//标明由哪个类执行校验逻辑
public @interface EnumString {
String message() default "value not in enum values.";
Class<?>[] groups() default {};
Class<? extends Payload>[] palyload() default {};
/**
* @return date must in this value array
*/
String[] value();
/**
* Defines several {@link EnumString} annotations on the same element.
*
* @see EnumString
*/
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@interface List {
EnumString[] value();
}
}
自定义校验逻辑
package com.didiplus.common.annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/26
* Desc:
*/
public class EnumStringValidator implements ConstraintValidator<EnumString,String> {
private List<String> enumStringList;
@Override
public void initialize(EnumString constraintAnnotation) {
enumStringList = Arrays.asList(constraintAnnotation.value());
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if(value == null) {
return true;
}
return enumStringList.contains(value);
}
}
在字段上增加注解
@ApiModelProperty(value = "性别")
@EnumString(value = {"F","M"}, message="性别只允许为F或M")
private String sex;
体验效果
分组校验
一个对象在新增的时候某些字段是必填,在更新是有非必填。如上面的 SysDictType
中 id
属性在新增操作时都是必填。 面对这种场景你会怎么处理呢?
其实 Validator
校验框架已经考虑到了这种场景并且提供了解决方案,就是分组校验。 要使用分组校验,只需要三个步骤:
定义分组接口
package com.didiplus.common.base;
import javax.validation.groups.Default;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/26
* Desc:
*/
public interface ValidGroup extends Default {
interface Crud extends ValidGroup{
interface Create extends Crud{
}
interface Update extends Crud{
}
interface Query extends Crud{
}
interface Delete extends Crud{
}
}
}
在模型中给参数分配分组
@Null(groups = ValidGroup.Crud.Create.class)
@NotNull(groups = ValidGroup.Crud.Update.class,message = "字典ID不能为空")
@ApiModelProperty("ID")
private String id;
体现效果
SpringBoot 如何进行参数校验的更多相关文章
- springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743
https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...
- 测试开发专题:如何在spring-boot中进行参数校验
上文我们讨论了spring-boot如何去获取前端传递过来的参数,那传递过来总不能直接使用,需要对这些参数进行校验,符合程序的要求才会进行下一步的处理,所以本篇文章我们主要讨论spring-boot中 ...
- SpringBoot 如何进行参数校验,老鸟们都这么玩的!
大家好,我是飘渺. 前几天写了一篇 SpringBoot如何统一后端返回格式?老鸟们都是这样玩的! 阅读效果还不错,而且被很多号主都转载过,今天我们继续第二篇,来聊聊在SprinBoot中如何集成参数 ...
- 【springboot】@Valid参数校验
转自: https://blog.csdn.net/cp026la/article/details/86495659 扯淡: 刚开始写代码的时候对参数的校验要么不做.要么写很多类似 if( xx == ...
- 【全网最全】springboot整合JSR303参数校验与全局异常处理
一.前言 我们在日常开发中,避不开的就是参数校验,有人说前端不是会在表单中进行校验的吗?在后端中,我们可以直接不管前端怎么样判断过滤,我们后端都需要进行再次判断,为了安全.因为前端很容易拜托,当测试使 ...
- SpringBoot - Bean validation 参数校验
目录 前言 常见注解 参数校验的应用 依赖 简单的参数校验示例 级联校验 @Validated 与 @Valid 自定义校验注解 前言 后台开发中对参数的校验是不可缺少的一个环节,为了解决如何优雅的对 ...
- springmvc、springboot 参数校验
参数校验在项目中是必不可少的,不仅前端需要校验,为了程序的可靠性,后端也需要对参数进行有效性的校验.下面将介绍在springmvc或springboot项目中参数校验的方法 准备工作: 引入校验需要用 ...
- 更加灵活的参数校验,Spring-boot自定义参数校验注解
上文我们讨论了如何使用@Min.@Max等注解进行参数校验,主要是针对基本数据类型和级联对象进行参数校验的演示,但是在实际中我们往往需要更为复杂的校验规则,比如注册用户的密码和确认密码进行校验,这个时 ...
- 补习系列(4)-springboot 参数校验详解
目录 目标 一.PathVariable 校验 二.方法参数校验 三.表单对象校验 四.RequestBody 校验 五.自定义校验规则 六.异常拦截器 参考文档 目标 对于几种常见的入参方式,了解如 ...
随机推荐
- Notion-douan:搭建自己的阅读清单
前言 交完论文盲审稿,终于从接近一年的实习.秋招和论文的忙碌中闲下来. 在复盘秋招的时候发现自己虽然看过不少书,但缺少整理和思考,所以想趁这个机会梳理一下自己的阅读习惯,希望以后再读新的东西可以更系统 ...
- XStream类的对象将javaBean转成XML
[省市联动] servlet端: //返回数据xml(XStream) XStream xStream = new XStream(); //把路径设置别名 xStream.alias("c ...
- python 装饰器函数基础知识
1.装饰器的本质--一个闭包函数 2.装饰器的功能--在不改变原函数及其调用方式情况下对原函数功能进行拓展 3.带参数和返回值的装饰器 def timer(func): @wraps(func) #使 ...
- java-开发规约
public class TenTen { /** * 代码中的命名不能用下划线或美元符号开始和结束:例如 _name name_ $name name$ */ /** * 类名必须使用UpperCa ...
- SpringBoot 自定义配置文件不会自动提示问题
参阅:https://www.jianshu.com/p/ec3f0b0371e6
- Spring Mvc 源代码之我见 二
上一篇简单介绍了spring mvc 的一些基本内容 和DispatcherServlet 的doc.这一篇将会继续写我对Spring Mvc 源代码的理解.直接上代码: /** * This imp ...
- spring @Bean和@Order 官方doc理解
今天阅读了spring的官方代码,(大概)理解了@Bean和@Order如何使用. @Bean 官方代码解读: 0.@Bean的注入,用于表示这个bean被spring容器管理(创建.销毁)(官方英文 ...
- 解决Project出来的问题
问题显现: 解决办法: 恢复默认布局
- 数据库学习之"清理表内所有数据"
今天在写定时任务的时候表内的数据都出现了问题,所以用了 1 truncate table 表名 来清空表内的数据
- 打造专属自己的html5拼图小游戏
最近公司刚好有个活动是要做一版 html5的拼图小游戏,于是自己心血来潮,自己先实现了一把,也算是尝尝鲜了.下面就把大体的思路介绍一下,希望大家都可以做出一款属于自己的拼图小游戏,必须是更炫酷,更好玩 ...