spring mvc @NotNull 传参验证
在spring mvc开发配合前端同事进行创建,修改操作的时候,需要验证参数的有效性。
在传统的方案里, 通过在代码里加 if else 实现
if (user.gietNmae() is null) {
// xxx
}else if user.getNum is null
// xxx
以上是传统方案,如果有多个地方判断参数的有效性,那么这段代码要写好几次(当能提成一个公共方法也可以)
下面介绍 通过 @NotNull 和 @Valid 参数来简单快速实现参数验证的方法。
- 在javabean 方法中给需要验证的参数上 加上 NotNull 注解
private Integer id;
@NotNull(message = "roleName 不能为空")
private String roleName;
@NotBlank(message = "roleCode 不能为空")
- 在需要验证地方 加入@vaild 参数 开启参数验证
public ResponseEntity insert(@Valid @RequestBody Role role {
return ResponseEntity.success(roleService.insert(role));
}
- 为了返回结果的友好化,可以通过 BindingResult 类,实现
public ResponseEntity insert(@Valid @RequestBody Role role, BindingResult result) {
if (result.hasErrors()) { // 参数验证出错
StringBuilder resultMsg = new StringBuilder();
result.getAllErrors().stream().forEach(error->{ // 拼接错误信息
resultMsg.append(error.getDefaultMessage());
resultMsg.append(", ");
});
System.out.println(resultMsg);
// 通过异常 抛给前端
throw new Exception(resultMsg.toString());
}
return ResponseEntity.success(roleService.insert(role));
}
跟多注解:
@Null 被注释的元素必须为null
@NotNull 被注释的元素不能为null
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须为false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min) 被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串必须非空
@Range 被注释的元素必须在合适的范围内
参考:
https://blog.youkuaiyun.com/weixin_41969587/article/details/88600296
https://blog.youkuaiyun.com/qq920447939/article/details/80198438