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. 2019-2020-1 20199326《Linux内核原理与分析》第七周作业

    实验内容:分析Linux内核创建一个新进程的过程 初始化Menu Os,输入fork可以看到menuos触发了一个fork系统调用 再开一个shell,进入调试模式,设置几个断点sys_clone,d ...

  2. XSS Challenge(1)

    XSS Challenges http://xss-quiz.int21h.jp/ Stage #1 注入alert(document.domain),先试一试输入后会返回什么: 返回在标签中,直接尝 ...

  3. Testing for the End of a File (Windows 的异步 IO)

    The ReadFile function checks for the end-of-file condition (EOF) differently for synchronous and asy ...

  4. python django mysql配置

    1    django默认支持sqlite,mysql, oracle,postgresql数据库.  <1> sqlite django默认使用sqlite的数据库,默认自带sqlite ...

  5. postman的使用概览

    本文主要描述postman的功能与使用方法Postman是404大厂的基于javascript语言完成的一款超级强大的插件,名字也很亲近(邮递员).可以用于做API请求测试.前端后台测试使用Postm ...

  6. php数组存在重复的相反元素,去重复

    $arr1=array('a_b','c_d','b_a','d_c'); $arr2=array('a_b','c_d','b_a','d_c'); 条件: a_b==b_a:c_d==d_c: 需 ...

  7. nodeJS生成xlsx以及设置样式

    参考: https://www.npmjs.com/package/xlsx-style https://www.jianshu.com/p/877631e7e411 https://sheetjs. ...

  8. PyCharm 集成 SVN,检出、提交代码

    1.安装 SVN,解决 SVN 目录中没有 svn.exe 问题 重新打开 TortoiseSVN 安装文件 选择 Modify 后在command line client tools 选项修改为 W ...

  9. 数据库SQL---范式

    1.数据冗余导致的问题:冗余存储.更新异常.插入异常.删除异常. 2.函数依赖:一种完整性约束. 在关系模式r(R)中,α属于R,β属于R. 1)α函数确定β(β函数依赖于α):记作α→β,对于任意合 ...

  10. ASP.NET Core3.x 基础—注册服务(2)

    这篇文章介绍在ASP.NET Core中注册一下自己的服务. 首先创建一个Services文件夹.在文件夹里面创建一个接口 IClock,以及两个类ChinaClock.UtcClock.这两个类分别 ...