我们在做Web开发的时候,前端页面需要提交一个表单信息给后端。后端开发人员一般是封装一个BO对象来进行接收的。但是用户在填写表单信息的时候难免会有些疏忽,所以后端一般都会对前端传递过来的数据进行一个校验。例如手机号的长度是否正确呀?邮箱格式呀?密码长度?用户姓名不能为空等等之类。
如果前端传递的参数比较少,我们可以直接使用if来进行判断
if(用户名为空){
//返回错误信息给前端页面
}
使用if非常方便,直观。但是如果前端页面传递参数太多,我们还是使用if来进行校验的话。可能就会写太多的重复类似的代码,这样看起来十分不美观,也确实增加我们的工作量。那么我们完全可以使用Hibernate验证用户信息。
由于我们使用的是SpringBoot框架。这个jar包已经包含在了spring-web-starter中了,无需我们再一次导入。这里已一个BO类的来进行演示和说明.。
我们只需要在校验的字段上加上相应的注解就可以了。
@NotBlank 字段不能为空
@Length 限制字段的长度
@Pattern 按照指定格式校验
@Email 邮箱格式校验
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.util.Date;
@ApiModel(value="用户对象", description="从客户端,由用户传入的数据封装在此entity中")
public class CenterUserBO {
@ApiModelProperty(value="用户名", name="username", example="json", required = false)
private String username;
@ApiModelProperty(value="密码", name="password", example="123456", required = false)
private String password;
@ApiModelProperty(value="确认密码", name="confirmPassword", example="123456", required = false)
private String confirmPassword;
@NotBlank(message = "用户昵称不能为空")
@Length(max = 12, message = "用户昵称不能超过12位")
@ApiModelProperty(value="用户昵称", name="nickname", example="杰森", required = false)
private String nickname;
@Length(max = 12, message = "用户真实姓名不能超过12位")
@ApiModelProperty(value="真实姓名", name="realname", example="杰森", required = false)
private String realname;
@Pattern(regexp = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$", message = "手机号格式不正确")
@ApiModelProperty(value="手机号", name="mobile", example="13999999999", required = false)
private String mobile;
@Email
@ApiModelProperty(value="邮箱地址", name="email", example="imooc@imooc.com", required = false)
private String email;
@Min(value = 0, message = "性别选择不正确")
@Max(value = 2, message = "性别选择不正确")
@ApiModelProperty(value="性别", name="sex", example="0:女 1:男 2:保密", required = false)
private Integer sex;
@ApiModelProperty(value="生日", name="birthday", example="1900-01-01", required = false)
private Date birthday;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "CenterUserBO{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", confirmPassword='" + confirmPassword + '\'' +
", nickname='" + nickname + '\'' +
", realname='" + realname + '\'' +
", mobile='" + mobile + '\'' +
", email='" + email + '\'' +
", sex=" + sex +
", birthday=" + birthday +
'}';
}
}
以下为Hibernate的相关校验注解
/**
* Bean Validation 中内置的 constraint
* @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(regex=,flag=) 被注释的元素必须符合指定的正则表达式
* Hibernate Validator 附加的 constraint
* @NotBlank(message =) 验证字符串非null,且长度必须大于0
* @Email 被注释的元素必须是电子邮箱地址
* @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
* @NotEmpty 被注释的字符串的必须非空
* @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
*/
使用注解@Valid开启参数校验。
BindingResult对象用来接收参数错误返回结果,可以返回给前端页面
如果你需要返回参数的错误信息可以用如下方式
//判断BindingResult中是否存在错误信息
if (result.hasErrors()) {
Map<String, String> errorMap = getErrors(result);
//错误信息用map来接收,返回map集合给前端
}
private Map<String, String> getErrors(BindingResult result) {
HashMap<String, String> map = new HashMap<>();
List<FieldError> errorList = result.getFieldErrors();
for (FieldError error : errorList) {
//发生验证错误所对应的某一个属性
String errorField = error.getField();
//验证错误信息
String errorMsg = error.getDefaultMessage();
map.put(errorField, errorMsg);
}
return map;
}