JSR303

使用步骤

1.依赖

 <!--数据校验-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>

2.在entity类的属性上添加注解

3.开启校验功能:在controller类的方法的参数上加上@Valid属性

4.校验失败的处理:

  • 第一种:单独处理
public R save(@Valid @RequestBody BrandEntity brand,BindingResult result){
if(result.hasErrors()){
Map<String,String> map = new HashMap<>();
//1、获取校验的错误结果
result.getFieldErrors().forEach((item)->{
//FieldError 获取到错误提示
String message = item.getDefaultMessage();
//获取错误的属性的名字
String field = item.getField();
map.put(field,message);
});
return R.error(400,"提交的数据不合法").put("data",map);
}else {
brandService.save(brand);
}
return R.ok();
}
  • 第二种,抛出异常后统一处理
  1. 定义@RestControllerAdvice处理请求异常类
  2. @ExceptionHandler(value= xxx.class)注解根据异常类型标注在方法上,编写处理逻辑
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice { @ExceptionHandler(value= MethodArgumentNotValidException.class)
public R handleValidException(MethodArgumentNotValidException e){
log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
BindingResult bindingResult = e.getBindingResult();
Map<String,String> errorMap = new HashMap<>();
bindingResult.getFieldErrors().forEach((error)->{
//存储校验字段名,以及校验字段失败提示
errorMap.put(error.getField(),error.getDefaultMessage());
});
return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
} @ExceptionHandler(value = Throwable.class)
public R handleException(Throwable throwable){ log.error("错误:",throwable);
return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
}
  1. 定义异常枚举类
public enum BizCodeEnume {
UNKNOW_EXCEPTION(10000,"系统未知异常"),
VAILD_EXCEPTION(10001,"参数格式校验失败");
private int code;
private String msg;
BizCodeEnume(int code,String msg){
this.code = code;
this.msg = msg;
} public int getCode() {
return code;
} public String getMsg() {
return msg;
}
}

关于不为空

  1. @NotNull

    只要不为空,校验任意类型

    The annotated element must not be {@code null}.

    Accepts any type.

  2. @NotBlank

    至少有一个非空字符,校验字符

    The annotated element must not be {@code null} and must contain at least one

    non-whitespace character. Accepts {@code CharSequence}.

  3. @NotEmpty

    非空,也不能内容为空,校验字符,集合,数组

    The annotated element must not be {@code null} nor empty. Supported types are:

    {@code CharSequence} (length of character sequence is evaluated)

    {@code Collection} (collection size is evaluated)

    {@code Map} (map size is evaluated)

    Array (array length is evaluated)

分组校验

步骤:

  1. 在校验注解上加上groups = {xxx.class, ...}属性,值可以是任意interface接口,例如

    @URL(message = "logo必须是一个合法的url地址",groups={AddGroup.class,UpdateGroup.class})

  2. 在开启校验处,将@Valid注解改为@Validated({xxx.class}),例如@Validated({AddGroup.class})就表示只校验该组的属性;

    注意:未添加任何分组的校验将会无效,开启娇艳的时候i如果添加了分组信息,那么只会校验同样页添加了该分组的属性。

自定义校验

1)、编写一个自定义的校验注解

@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ListValue {
String message() default "{com.lx.common.valid.ListValue.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; int[] vals() default { };
}

2)、编写配置文件ValidationMessages.properties,给自定义的校验配置校验失败的信息

com.lx.common.valid.ListValue.message=显示状态只能为1或0

3)、编写一个自定义的校验器 ConstraintValidator

​ 实现ConstraintValidator接口,第一个参数为绑定的校验注解名,第二个参数为校验的属性类型,完成初始化与判断方法。

public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {

    private Set<Integer> set = new HashSet<>();
/**
* @Description: 根据注解中的属性初始化
* @Param0: constraintAnnotation
**/
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
for (int val:vals) {
set.add(val);
}
} /**
* @Description: 判断校验是否成功
* @Param0: value 被校验值
* @Param1: context
**/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}

4)、关联自定义的校验器和自定义的校验注解

@Constraint(validatedBy = { ListValueConstraintValidator.class })

5)、使用

@NotNull(groups = {AddGroup.class, UpdateGroup.class})
@ListValue(vals = {0,1},groups = {AddGroup.class,UpdateGroup.class})
private Integer showStatus;

完整代码

controller

/**
* 保存
*/
@RequestMapping("/save")
public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand){
brandService.save(brand); return R.ok();
} /**
* 修改
*/
@RequestMapping("/update")
public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand){
brandService.updateById(brand); return R.ok();
}

entity

@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
private static final long serialVersionUID = 1L; /**
* 品牌id
*/
@NotNull(message = "修改必须指定品牌id",groups = {UpdateGroup.class})
@Null(message = "新增不能指定id",groups = {AddGroup.class})
@TableId
private Long brandId;
/**
* 品牌名
*/
@NotBlank(message = "品牌名必须提交",groups = {AddGroup.class,UpdateGroup.class})
private String name;
/**
* 品牌logo地址
*/
@URL(message = "logo必须是一个合法的url地址",groups={AddGroup.class,UpdateGroup.class})
private String logo;
/**
* 介绍
*/
private String descript;
/**
* 显示状态[0-不显示;1-显示]
*/
@NotNull(groups = {AddGroup.class, UpdateGroup.class})
@ListValue(vals = {0,1},groups = {AddGroup.class,UpdateGroup.class})
private Integer showStatus;
/**
* 检索首字母
*/
@NotEmpty(groups={AddGroup.class})
@Pattern(regexp="^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups={AddGroup.class,UpdateGroup.class})
private String firstLetter;
/**
* 排序
*/
@NotNull(groups={AddGroup.class})
@Min(value = 0,message = "排序必须大于等于0",groups={AddGroup.class,UpdateGroup.class})
private Integer sort; }

测试1:

测试2:

JSR303后端校验详细笔记的更多相关文章

  1. JSR303后端校验(一)

    JSR303后端校验(一) (1)在pom文件中添加依赖 <!-- JSR303后端校验 --> <dependency> <groupId>org.hiberna ...

  2. JSR303 后端校验包的使用

    1.首先通过Maven导入JSR303架包. <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate- ...

  3. springboot超详细笔记

    一.Spring Boot 入门 1.Spring Boot 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案: 2.微服务 2014,m ...

  4. (转载)Linux下安装配置MySQL+Apache+PHP+WordPress的详细笔记

    Linux下安装配置MySQL+Apache+PHP+WordPress的详细笔记 Linux下配LMAP环境,花了我好几天的时间.之前没有配置过,网上的安装资料比较混乱,加上我用的版本问题,安装过程 ...

  5. 写给后端的前端笔记:浮动(float)布局

    写给后端的前端笔记:浮动(float)布局 这篇文章主要面向后端人员,对前端有深刻了解的各位不喜勿喷. 起因 前一阵子我一个后端的伙伴问我,"前端的左飘怎么做?",我立马就懵了,& ...

  6. 写给后端的前端笔记:定位(position)

    写给后端的前端笔记:定位(position) 既然都写了一篇浮动布局,干脆把定位(position)也写了,这样后端基本上能学会css布局了. 类别 我们所说的定位position主要有三类:固定定位 ...

  7. 【spring】-- jsr303参数校验器

    一.为什么要进行参数校验? 当我们在服务端控制器接受前台数据时,肯定首先要对数据进行参数验证,判断参数是否为空?是否为电话号码?是否为邮箱格式?等等. 这里有个问题要注意: 前端代码一般上会对这些数据 ...

  8. xshell远程终端操作Ubuntu server安装LAMP环境之最详细笔记之二PHP开发环境配置

    前言: 昨天学会了安装server,今天试着通过远程终端xshell来安装LAMP,搭配一下开发环境,也有集成环境可以一键安装使用,还是瞎折腾一下,手动一步一步搭建一下这个开发环境. 接上一篇:ubu ...

  9. SpringMVC 使用JSR-303进行校验 @Valid

    注意:1 public String save(@ModelAttribute("house") @Valid House entity, BindingResult result ...

随机推荐

  1. 关于宝塔下的项目中的php不能访问的问题

    遇到的问题是访问项目根目录的所有php文件都是报404错,而其他文件则可以,比如txt,最后查资料发现 在宝塔运行网站的时候会在项目的根目录自动生成一个.user.ini文件,这个文件主要是防止对指定 ...

  2. 20199310《Linux内核原理与分析》第十二周作业

    1.问题描述 2014年9月24日,Bash中发现了一个严重漏洞shellshock,该漏洞可用于许多系统,并且既可以远程也可以在本地触发.在本实验中,通过学习重现攻击该漏洞,加深对于ShellSho ...

  3. Linux系统硬件时间12小时制和24小时制表示设置

    目前的服务器status是下面这样的 服务器系统    centos7 Linux系统时间      Fri Mar 20 15:26:27 CST 2020 Linux系统硬件时间  Fri 20 ...

  4. Python 基础教程(第二版)笔记 (2) 字典

    P59 字典方法 1. clear 2. copy, deepcopy 3. fromkeys 4. get 比下标安全 5. has_key 6. items, iteritems 7. keys, ...

  5. java中ThreadPool的介绍和使用

    文章目录 Thread Pool简介 Executors, Executor 和 ExecutorService ThreadPoolExecutor ScheduledThreadPoolExecu ...

  6. Linux系统管理第六次作业 进程和计划任务管理

    1.通过ps命令的两种选项形式查看进程信息 [root@localhost ~]# ps aux USER        PID %CPU %MEM    VSZ   RSS TTY      STA ...

  7. Robot Framework -002 在Windows10上的安装

    机器人框架是使用Python实现的,并且还支持Jython(JVM),IronPython(.NET)和PyPy. 在安装框架之前,一个明显的前提条件是至少安装这些解释器之一. 下面列出了安装Robo ...

  8. 【Linux网络基础】上网原理流程

    1. 局域网用户上网原理 上网过程说明: 确保物理设备和线路架构准备完毕,并且线路通讯状态良好 终端设备需要获取或配置上局域网(私有地址)地址,作为局域网网络标识 当终端设备想上网时,首先确认访问的地 ...

  9. 标准库模块time,datetime

    在Python中,通常有这几种方式来表示时间: 1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素. 由于Python的time模块实现主要调用C库,所以各个平台可能有所 ...

  10. 为什么LIKELY和UNLIKELY要用两个叹号

    LIKELY和UNLIKELY的一般定义如下: #define LIKELY(x) (__builtin_expect(!!(x),1))#define UNLIKELY(x) (__builtin_ ...