__震惊了!,一遍一遍在业务逻辑中编写的验证条件被抽离了!

是什么:


-

Java Specification Requests 303 ,用于对javaBean 属性的验证。

-


解决了什么问题:


-

1. 业务中充斥着对javabean属性的验证,这些都是很必要的验证,不能缺少,但是又让代码变得不那么可读,也不方便代码的维护,使用jsr303的相关技术,

就把对bean的验证抽取了出来,是业务代码更清晰。

-


要点:


-

1. 使用Bean Validation 的参考实现,如果使用jpa,那么就已经有了;
2. 使用注解限制bean的属性;
3. 在控制器方法中使用Vaild注解,表示当前参数需要被验证;
4. 紧随Valid注解写上Errors参数,用于接收验证参数时候产生的错误;
5. 如果觉得默认的注解不够用,完全可以自定义自己的验证注解。

-


demo1 【基本使用】:


-

pojo:

_

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Past;
import java.util.Date; public class Person {
@NotEmpty(message = "姓名不能为空")
private String username;
@Past(message = "生日只能是过去的日期")
private Date birthday;

// 省略其他方法
}

  

_

controller:

_

@RestController
@RequestMapping("/t")
public class TestController { @PostMapping
public Object binderTest(@RequestBody @Valid Person p, Errors errors) throws Exception {
if(errors.hasErrors()){
throw new Exception(errors.getFieldErrors().toString());
}else{
// do something
// do something
return p;
}
}
}

  

_

截图:

-


demo02:【自定义constraint】


-

1.  编写验证所需要的注解;

2. 实现javax.validation.ConstraintValidator接口,可以使用Autowired注解注入其他服务进来;

3.覆写boolean isValid(T value, ConstraintValidatorContext context);方法,完成校验的逻辑;

代码:

///////////////////////////////////////////////////////////////////////
///注解///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*; @Constraint(validatedBy = {StatusValidator.class})
@Documented
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
String message() default "不正确的状态 , 应该是 'created', 'paid', shipped', closed'其中之一"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
} ///////////////////////////////////////////////////////////////////////
///验证器//////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays; public class StatusValidator implements ConstraintValidator<Status, String> { // 特别复杂的验证可能需要我们注入多个服务,也有可能一些验证需要查询数据库
@Autowired
private UserService userService; private final String[] ALL_STATUS = {"created", "paid", "shipped", "closed"}; public void initialize(Status status) { }
// 验证方法,此方法中可以调用注入的服务,可以对数据库进行查询~
public boolean isValid(String value, ConstraintValidatorContext context) { User lhn = userService.findUserByUsername("lhn");
System.out.println(lhn); if(Arrays.asList(ALL_STATUS).contains(value))
return true;
return false;
}
} ///////////////////////////////////////////////////////////////////////
///使用///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
public class Person {
@NotEmpty(message = "姓名不能为空")
private String username;
@Past(message = "生日只能是过去的日期")
private Date birthday;
@Status
private String status;
}

  

-


SpringBoot#JSR303的更多相关文章

  1. [SpringBoot] - 配置文件的多种形式及JSR303数据校验

    Springboot配置文件: application.yml   application.properties(自带) yml的格式写起来稍微舒服一点 在application.properties ...

  2. Springboot:JSR303数据校验(五)

    @Validated //开启JSR303数据校验注解 校验规则如下: [一]空检查 @Null 验证对象是否为null @NotNull 验证对象是否不为null, 无法查检长度为0的字符串 @No ...

  3. SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后端篇(一): 搭建基本环境、整合 Swagger、MyBatisPlus、JSR303 以及国际化操作

    相关 (1) 相关博文地址: SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(一):搭建基本环境:https://www.cnblogs.com/l-y- ...

  4. SpringBoot第七集:异常处理与整合JSR303校验(2020最新最易懂)

    SpringBoot第七集:异常处理与整合JSR303校验(2020最新最易懂) 一.SpringBoot全局异常 先讲下什么是全局异常处理器? 全局异常处理器就是把整个系统的异常统一自动处理,程序员 ...

  5. 【全网最全】springboot整合JSR303参数校验与全局异常处理

    一.前言 我们在日常开发中,避不开的就是参数校验,有人说前端不是会在表单中进行校验的吗?在后端中,我们可以直接不管前端怎么样判断过滤,我们后端都需要进行再次判断,为了安全.因为前端很容易拜托,当测试使 ...

  6. SpringBoot 使用 JSR303 自定义校验注解

    JSR303 是 Java EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是hibernate Validator,有了它,我们可以在实体类的字段上标注不同的注解实现对数 ...

  7. 4 — springboot中的jsr303检验

    1.导入依赖 <!--JSR303校验的依赖 --> <dependency> <groupId>org.springframework.boot</grou ...

  8. springboot配置(yami配置文件,JSR303数据校验,多环境配置)

    yami配置文件 YAML是 "YAML Ain't a Markup Language" (YAML不是一种标记语言)的递归缩写.在开发的这种语言时,YAML 的意思其实是:&q ...

  9. SpringBoot 之 JSR303 数据校验

    使用示例: @Component @ConfigurationProperties(prefix = "person") @Validated //使用数据校验注解 public ...

随机推荐

  1. angular 自定义服务封装自定义http请求

    在angular中将http请求,放置在一起封装成服务,可减少代码重复,方便使用 var ngpohttprest = angular.module('ngpohttprest', []); ngpo ...

  2. php 增删改查范例(2)

    增加页面add.php: <!DOCTYPE html><html lang="en"><head>    <meta charset=& ...

  3. markdown基本语法教程

    标题 一级标题 二级标题 三级标题 以此类推,总共六级标题,建议在警号后面加一个空格,这是最标准的markdown语法 列表 在markdown下: 列表的显示只需要在文字前加上-.+或*即可变为无序 ...

  4. Codeforces 598D:Igor In the Museum

    D. Igor In the Museum time limit per test 1 second memory limit per test 256 megabytes input standar ...

  5. Linux 创建网卡子接口

    创建网卡子接口,添加IP别名 ifconfig eth0:0  2.2.2.2/24 或 ip addr add 2.2.2.2/24 dev eth0 label eth0:0 清除网卡子接口,删除 ...

  6. jenkins 2.204.2 安装, 使用国内源安装, 并且跳过插件界面, 更新成国内插件源.

    需要java环境支持,自行百度. jenkins 安装源在国外, 下载会比较慢, 尤其在linux下, 使用yum或者apt install jenkins方式安装时,经常会下载失败. 由于yum或者 ...

  7. canvas的其他应用

    画布的基础知识 专门研究画布的大佬 手动实现echar的大佬 echar官方 画布之水印 ctx.font = "bold 20px Arial"; ctx.lineWidth = ...

  8. luogu P2766 最长不下降子序列问题

    第一问可以直接DP来做,联想上一题,线性规划都可以化为网络流?我们可以借助第一问的DP数组,来建立第二问第三问的网络流图,考虑每一种可能,都是dp数组中满足num[i]>=num[j]& ...

  9. 【Luogu4448】 [AHOI2018初中组]球球的排列

    题意 有 \(n\) 个球球,每个球球有一个属性值 .一个合法的排列满足不存在相邻两个球球的属性值乘积是完全平方数.求合法的排列数量对 \(10^9+7\) 取膜. \(n\le 300\) (本题数 ...

  10. C# webkit 内核浏览器 访问https 网站 提示 Problem with the SSL CA cert (path? access rights?)

    C# webkit 内核浏览器 访问https 网站 提示 Problem with the SSL CA cert (path? access rights?) 解决方法: 陈凯文11112014- ...