参数校验在项目中是必不可少的,不仅前端需要校验,为了程序的可靠性,后端也需要对参数进行有效性的校验。下面将介绍在springmvc或springboot项目中参数校验的方法

准备工作:

引入校验需要用到的依赖

首先放上我们的测试对象

方法一、全部使用注解的方式进行校验

可以看到,我们在测试对象中加上了@NotBlank和@NotEmpty注解,表示该字段需要进行校验,下面我们进行测试

我们在需要校验的对象前面加上@Valid注解

测试方法:

运行结果:

这样我们就完成了参数校验,并且获取到了错误的信息。但是需要注意的是,我们想要拿到错误信息的时候还需要用到BindingResult对象,如果项目中有多处需要进行校验的话,BindResult参数用到得特别频繁,导致代码看起来很多余,所以我们使用第二种方法,自定义参数校验。

方法二、自定义参数校验方法

自定义校验类的代码如下

package com.me.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.me.exception.ParamException;
import org.apache.commons.collections.MapUtils; import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*; public class BeanValidator {
// Validator工厂
private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // Map<String,String> 中 key表示错误的字段,value表示错误信息 /**
* 校验单个对象
*
* @param t
* @param groups
* @param <T>
* @return
*/
public static <T> Map<String, String> validate(T t, Class... groups) {
Validator validator = validatorFactory.getValidator();
// 传入参数,并获取校验结果
Set validatorErrors = validator.validate(t, groups);
// 若校验为空,说明校验通过,返回空集合
if (validatorErrors.isEmpty()) {
return Collections.emptyMap();
} else {
LinkedHashMap<String, String> errors = Maps.newLinkedHashMap();
// 对校验错误信息进行遍历
Iterator iterator = validatorErrors.iterator();
while (iterator.hasNext()) {
ConstraintViolation violation = (ConstraintViolation) iterator.next();
// 放入key,value
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errors;
}
} /**
* 校验多个对象
*
* @param collection
* @return
*/
public static Map<String, String> validateList(Collection<?> collection) {
// 判断是否为空,为空时抛出异常
Preconditions.checkNotNull(collection);
Iterator iterator = collection.iterator();
Map errors;
do {
if (!iterator.hasNext()) {
return Collections.emptyMap();
}
// 取到当前值
Object object = iterator.next();
errors = validate(object, new Class[0]);
} while (errors.isEmpty());
return errors;
} public static Map<String, String> validateObject(Object first, Object... objects) { if (objects != null && objects.length > 0) {
return validateList(Lists.asList(first, objects));
} else {
return validate(first, new Class[0]);
}
} public static void check(Object param) throws ParamException {
Map<String, String> errors = validateObject(param);
if (MapUtils.isNotEmpty(errors)) {
throw new ParamException(errors.toString());
} } }

我们对抛出的异常进行了全局捕获

同样,我们需要标志校验规则

测试方法:

运行结果:

springmvc、springboot 参数校验的更多相关文章

  1. 补习系列(4)-springboot 参数校验详解

    目录 目标 一.PathVariable 校验 二.方法参数校验 三.表单对象校验 四.RequestBody 校验 五.自定义校验规则 六.异常拦截器 参考文档 目标 对于几种常见的入参方式,了解如 ...

  2. springboot 参数校验详解

    https://www.jianshu.com/p/89a675b7c900 在日常开发写rest接口时,接口参数校验这一部分是必须的,但是如果全部用代码去做,显得十分麻烦,spring也提供了这部分 ...

  3. SpringBoot 参数校验的方法

    Introduction 有参数传递的地方都少不了参数校验.在web开发中,前端的参数校验是为了用户体验,后端的参数校验是为了安全.试想一下,如果在controller层中没有经过任何校验的参数通过s ...

  4. 实用———springmvc接收参数校验

    https://www.cnblogs.com/funyoung/p/8670550.html https://www.cnblogs.com/monkeydai/p/10068547.html He ...

  5. SpringBoot 参数校验

    一.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  6. springboot参数校验

    为了能够进行嵌套验证,必须手动在Item实体的props字段上明确指出这个字段里面的实体也要进行验证.由于@Validated不能用在成员属性(字段)上,但是@Valid能加在成员属性(字段)上,而且 ...

  7. SpringMVC参数校验,包括JavaBean和基本类型的校验

    该示例项目使用SpringBoot,添加web和aop依赖. SpringMVC最常用的校验是对一个javaBean的校验,默认使用hibernate-validator校验框架.而网上对校验单个参数 ...

  8. SpringMVC参数校验(针对`@RequestBody`返回`400`)

    SpringMVC参数校验(针对@RequestBody返回400) 前言 习惯别人帮忙做事的结果是自己不会做事了.一直以来,spring帮我解决了程序运行中的各种问题,我只要关心我的业务逻辑,设计好 ...

  9. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

随机推荐

  1. Linux 一些使用工具

    ssh 链接使用工具xshell 下载链接 http://www.onlinedown.net/soft/36383.htm 映射硬盘工具 sftpdriver 安装输入服务器之后链接 并且输入注册码 ...

  2. 数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

    数据中包含日期.时间类型的数据可以通过 pandas 的 to_datetime 转换成 datetime 类型,方便提取各种时间信息 1 将 object 类型数据转成 datetime64 1&g ...

  3. CodeForces - 651C Watchmen (去重)

    Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn t ...

  4. UVA - 12333 Revenge of Fibonacci (大数 字典树)

    The well-known Fibonacci sequence is defined as following: F(0) = F(1) = 1 F(n) = F(n − 1) + F(n − 2 ...

  5. 微信小程序配置合法域名和业务域名

    在微信小程序的开发过程中,当需要请求第三方网站数据时,都是直接调用wx.request接口的: xxxx:function(){ wx.request({ url: 'xxxxxxxxxx', dat ...

  6. PP: DeepAR: probabilistic forecasting with autoregressive recurrent networks

    FROM Amazon research Germany PROBLEM probabilistic forecasting: estimate the probability distributio ...

  7. Selenium3+python自动化007-警告框

    警告框 alert = driver.switch_to.alert alert.text() alert.accpet() alert.dismiss() # 导selenium包 from sel ...

  8. [转]shallow heap & retained heap

    所有包含Heap Profling功能的工具(MAT, Yourkit, JProfiler, TPTP等)都会使用到两个名词,一个是Shallow Size,另一个是 Retained Size.  ...

  9. JDBC——DriverManager驱动管理对象

    功能 1.注册驱动 注册驱动:告诉程序使用哪个驱动jar包 写代码使用:Class.forName("com.mysql.jdbc.Driver"); 查看源码 mysql-con ...

  10. 环境配置 | mac环境变量文件.bash_profile相关

    每次环境配置都费老劲,零零碎碎的知识就记在这里 文件:~/.bash_profile