还在用if else进行数据校验?一招教你轻松搞定后端数据校验(对象、集合)
1、为什么要做数据校验?
对于任何一个应用而言,客户端做的数据有效性验证都不是安全有效的,而数据验证又是一个企业级项目架构上最为基础的功能模块,这时候就要求我们在服务端接收到数据的时候也对数据的有效性进行验证。为什么这么说呢?往往我们在编写程序的时候都会感觉后台的验证无关紧要,毕竟客户端已经做过验证了,后端没必要在浪费资源对数据进行验证了,但恰恰是这种思维最为容易被别人钻空子。毕竟只要有点开发经验的都知道,我们完全可以模拟 HTTP 请求到后台地址,模拟请求过程中发送一些涉及系统安全的数据到后台,后果可想而知…
2、如何利用SpringBoot如何轻松搞定数据校验
1、导入依赖(在 pom.xml 中添加上 spring-boot-starter-web 的依赖即可)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、改造实体类(验证的属性上加上验证规则注解)
public class WfylTemplate extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
private Long id;
/** 模板名称 */
@NotEmpty(message = "模板名称不能为空")
@Size(min = 1, max = 100,message = "长度在20-100")
private String templateName;
/** 表名 */
@NotEmpty(message = "表名称不能为空")
@Size(min = 1, max = 30,message = "长度在1-30")
@Pattern(regexp = "(^_([a-zA-Z0-9]_?)*$)|(^[a-zA-Z](_?[a-zA-Z0-9])*_?$)", message = "表名格式错误")
private String tableName;
}
3、改造控制器(需要验证的类上加上注解:@Validated)
BusinessType.INSERT)
@PostMapping
public AjaxResult add( @RequestBody @Validated WfylTemplate wfylTemplate)
{
return toAjax(wfylTemplateService.insertWfylTemplate(wfylTemplate));
}
4、全局异常捕获器
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BindException.class)
public AjaxResult validatedBindException(BindException e)
{
log.error(e.getMessage(), e);
String message = e.getAllErrors().get(0).getDefaultMessage();
return AjaxResult.error(message);
}
@ExceptionHandler(value = ConstraintViolationException.class)
public AjaxResult handleMethodArgumentNotValidException(ConstraintViolationException ex) {
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
PathImpl pathImpl = (PathImpl) constraintViolation.getPropertyPath();
// 读取参数字段,constraintViolation.getMessage() 读取验证注解中的message值
String paramName = pathImpl.getLeafNode().getName();
String message = "参数{".concat(paramName).concat("}").concat(constraintViolation.getMessage());
return AjaxResult.error(message);
}
return AjaxResult.error(ex.getMessage());
}
}
5、接口与测试
如何对集合里面的对象进行校验?
踩坑了,踩坑了,按照上面的方式对集合里面的对象进行验证,不用多想,肯定是不行的,不信?你们自己踩坑去。问题来了,怎么解锁验证的新姿势?
1、实体类改造(加上验证注解)
public class WfylTemplateFiled extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
private Long id;
/** 模板id */
private Long templateId;
/** 字段名称 */
@NotEmpty(message = "表名称不能为空")
@Pattern(regexp = "(^_([a-zA-Z0-9]_?)*$)|(^[a-zA-Z](_?[a-zA-Z0-9])*_?$)", message = "字段名称格式错误")
private String filedName;
/** 字段描述 */
private String filedDesc;
/** 字段类型 */
@NotEmpty(message = "字段类型不能为空")
private String filedType;
/** 字段长度 */
@Min(1)
@Max(255)
private Integer filedLength;
}
2、新增VO类,在集合上加上注解:@Valid
public class WfylTemplateVO implements Serializable
{
@Valid
private List<WfylTemplateFiled> wfylTemplateFileds ;
}
3、改造Controller
@PostMapping("{templateId}")
public AjaxResult add(@RequestBody @Validated WfylTemplateVO wfylTemplateFileds, @PathVariable Long templateId)
{
return toAjax(wfylTemplateFiledService.insertWfylTemplateFiledList(wfylTemplateFileds.getWfylTemplateFileds(),templateId