Validator一般用来验证前端页面传过来的数据 是否符合预期
首先在需要检验的pojo中对需要检验的属性加相关注解如下:
package com.aekc.mmall.param;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class UserParam {
private Integer id;
@NotBlank(message = "用户名不能为空")
@Length(min = 1, max = 20, message = "用户名长度")
private String username;
@NotBlank(message = "电话不可以为空")
@Length(min = 1, max = 13, message = "电话长度需要在13个字符以内")
private String telephone;
@Email
@NotBlank(message = "邮箱不能为空")
private String mail;
@NotNull(message = "必须指定用户状态")
@Min(value = 0, message = "用户状态不合法")
@Max(value = 1, message = "用户状态不合法")
private Integer status;
}
- 1.@NotNull注解: eg:如果传过来的noticeType为空,则会报如下错误
@NotBlank(message="类型不能为空") private String noticeType;
- @NotNull:不能为null,但可以为empty
- @NotEmpty:不能为null,而且长度必须大于0
@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
案例: -
1.String name = null; @NotNull: false @NotEmpty:false @NotBlank:false
-
2.String name = ""; @NotNull:true @NotEmpty: false @NotBlank: false
-
3.String name = " "; @NotNull: true @NotEmpty: true @NotBlank: false
-
4.String name = "Great answer!"; @NotNull: true @NotEmpty:true @NotBlank:true
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用户名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="状态",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id数组",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
}
注意在使用@NotBlank等注解时,一定要和@valid一起使用,不然@NotBlank不起作用(不用注解也可以,可以写类。。校验的两种方式1.加注解@Valid(这种方式后台会直接500错误,不友好) 2.可以写类,可以自定义抛出异常,)
-
-
检验类:
public class ValidatorUtils { private static Validator validator; static { validator = Validation.buildDefaultValidatorFactory().getValidator(); } /** * 校验对象 * @param object 待校验对象 * @param groups 待校验的组 * @throws RRException 校验不通过,则报RRException异常 */ public static void validateEntity(Object object, Class<?>... groups) throws RRException { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (!constraintViolations.isEmpty()) { StringBuilder msg = new StringBuilder(); for(ConstraintViolation<Object> constraint: constraintViolations){ msg.append(constraint.getMessage()).append("<br>"); } throw new RRException(msg.toString()); } } }
- 这是Controller:
-
@PostMapping("noticeList") @ApiOperation("通知/公告列表") public R noticeList(@RequestBody UsNoticePram form){ //表单校验 ValidatorUtils.validateEntity(form);
-
}