JSR303后端校验详细笔记
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();
}
- 第二种,抛出异常后统一处理
- 定义
@RestControllerAdvice处理请求异常类 - 将
@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());
}
}
- 定义异常枚举类
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;
}
}
关于不为空
@NotNull
只要不为空,校验任意类型
The annotated element must not be {@code null}.
Accepts any type.
@NotBlank
至少有一个非空字符,校验字符
The annotated element must not be {@code null} and must contain at least one
non-whitespace character. Accepts {@code CharSequence}.
@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)
分组校验
步骤:
在校验注解上加上
groups = {xxx.class, ...}属性,值可以是任意interface接口,例如@URL(message = "logo必须是一个合法的url地址",groups={AddGroup.class,UpdateGroup.class});在开启校验处,将
@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后端校验详细笔记的更多相关文章
- JSR303后端校验(一)
JSR303后端校验(一) (1)在pom文件中添加依赖 <!-- JSR303后端校验 --> <dependency> <groupId>org.hiberna ...
- JSR303 后端校验包的使用
1.首先通过Maven导入JSR303架包. <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate- ...
- springboot超详细笔记
一.Spring Boot 入门 1.Spring Boot 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案: 2.微服务 2014,m ...
- (转载)Linux下安装配置MySQL+Apache+PHP+WordPress的详细笔记
Linux下安装配置MySQL+Apache+PHP+WordPress的详细笔记 Linux下配LMAP环境,花了我好几天的时间.之前没有配置过,网上的安装资料比较混乱,加上我用的版本问题,安装过程 ...
- 写给后端的前端笔记:浮动(float)布局
写给后端的前端笔记:浮动(float)布局 这篇文章主要面向后端人员,对前端有深刻了解的各位不喜勿喷. 起因 前一阵子我一个后端的伙伴问我,"前端的左飘怎么做?",我立马就懵了,& ...
- 写给后端的前端笔记:定位(position)
写给后端的前端笔记:定位(position) 既然都写了一篇浮动布局,干脆把定位(position)也写了,这样后端基本上能学会css布局了. 类别 我们所说的定位position主要有三类:固定定位 ...
- 【spring】-- jsr303参数校验器
一.为什么要进行参数校验? 当我们在服务端控制器接受前台数据时,肯定首先要对数据进行参数验证,判断参数是否为空?是否为电话号码?是否为邮箱格式?等等. 这里有个问题要注意: 前端代码一般上会对这些数据 ...
- xshell远程终端操作Ubuntu server安装LAMP环境之最详细笔记之二PHP开发环境配置
前言: 昨天学会了安装server,今天试着通过远程终端xshell来安装LAMP,搭配一下开发环境,也有集成环境可以一键安装使用,还是瞎折腾一下,手动一步一步搭建一下这个开发环境. 接上一篇:ubu ...
- SpringMVC 使用JSR-303进行校验 @Valid
注意:1 public String save(@ModelAttribute("house") @Valid House entity, BindingResult result ...
随机推荐
- JVM 真的很难学么?不、只是你“不敢学”而已
JVM 真的很难学么?不.只是你"不敢学"而已 许多招聘的信息上面都说,要了解jvm.多线程什么的对于 java 程序员来说,这是工作好多年的程序员都不一定能掌握的东 ...
- [wp]xctf newscenter
手工注入 查询所有数据库名称和表名 ' union select 1,table_schema,table_name from information_schema.tables# 发现就两个数据库i ...
- 闲聊http1.1的6个方法
GET :获取资源GET 方法用来请求访问已被 URI 识别的资源.指定的资源经服务器端解析后返回响应内容. POST :传输实体主体POST 方法用来传输实体的主体.虽然用 GET 方法也可以传输实 ...
- 文件上传漏洞(pikachu)
文件上传漏洞 文件上传功能在web应用系统很常见,比如很多网站注册的时候需要上传头像,附件等等.当用户点击上传按钮后,后台会对上传的文件进行判断,比如是否是指定的类型.后缀名.大小等等,然后将其按照设 ...
- Linux下解压rar压缩包
wget http://www.rarlab.com/rar/rarlinux-x64-4.2.0.tar.gz rar软件不需要安装,直接解压到/usr/local下,以下操作需要有root权限. ...
- java 8中 predicate chain的使用
目录 简介 基本使用 使用多个Filter 使用复合Predicate 组合Predicate Predicate的集合操作 总结 java 8中 predicate chain的使用 简介 Pred ...
- Json & pickle 数据序列化
前提: 文本文件中只能写入字符串或ascii码格式的内容. info={'name':'zoe','age':18} f=open('test.txt','w') f.write(info) #在文本 ...
- Codeforce-Ozon Tech Challenge 2020-D. Kuroni and the Celebration(交互题+DFS)
After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Ital ...
- Codeforces 1291 Round #616 (Div. 2) C. Mind Control(超级详细)
C. Mind Control You and your n−1 friends have found an array of integers a1,a2,-,an. You have decide ...
- P3306 [SDOI2013]随机数生成器(bzoj3122)
洛谷 bzoj 特判+多测真恶心 . \(0\le a\le P−1,0\le b\le P−1,2\le P\le 10^9\) Sample Input 3 7 1 1 3 3 7 2 2 2 0 ...