前言
我想大家在寫代碼時都遇到過進行參數校驗吧,大家是否厭煩的在代碼裏寫上一堆if-else的參數校驗,既不優雅也浪費時間,那麼有沒有什麼省事的方式來進行參數校驗呢?SpringBoot爲我們集成了hibernate-validator來進行校驗,下面就讓我們來看看如何使用hibernate-validator吧
hibernate-validator使用方法
1.不用修改pom文件
從圖中可以看出在Springboot中本身就引用了hibernate-validator
2.在對象上添加註解
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=) 被註釋的元素必須在合適的範圍內
3.在controller中給需要校驗的對象前面增加@Valid
註解,並增加BindingResult
參數
@Valid 用來開啓校驗
BindingResult 接收校驗結果
4.方法說明
- BindingResult.hasErrors 是否有錯誤信息 返回值boolean
- BindingResult.getFieldErrors 獲取錯誤信息list 返回值List
- FieldError.getField() 發生驗證錯誤所對應的某一個屬性
- FieldError.getDefaultMessage 驗證錯誤的信息
代碼示例
使用場景:用戶修改基本信息,判斷信息輸入是否符合規則
實體類
package com.demo.pojo;
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="[email protected]", 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 +
'}';
}
}
Controller
package com.demo.controller;
import com.demo.pojo.CenterUserBO
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("userInfo")
public class CenterUserController {
@ApiOperation(value = "修改用戶信息", notes = "修改用戶信息", httpMethod = "POST")
@PostMapping("update")
public void update(
@ApiParam(name = "userId", value = "用戶id", required = true)
@RequestParam String userId,
@RequestBody @Valid CenterUserBO centerUserBO,
BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
if(result.hasErrors()){
Map<String,String> map = getErrors(result);
System.out.println(map.toString());
}
}
private Map<String,String> getErrors(BindingResult result){
Map<String,String> map = new HashMap<>();
List<FieldError> list = result.getFieldErrors();
for(FieldError error : list){
// 發生驗證錯誤所對應的某一個屬性
String errorField = error.getField();
// 驗證錯誤的信息
String errorMsg = error.getDefaultMessage();
map.put(errorField,errorMsg);
}
return map;
}
}