1、添加依賴
添加 Hibernate-Validator 依賴,如果使用了springboot,則不需要引用任何依賴,因為spring-boot-starter-web包中已經包含了Hibernate-Validator 依賴
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.7.Final</version>
</dependency>
2、常用校驗注解
3、具體使用
實體類中對響應的屬性進行判斷,加上響應注解即可
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@TableName("user")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 使用者ID
*/
@TableId
private Long userId;
/**
* 使用者名
*/
@NotBlank(message="使用者名不能為空", groups = {AddGroup.class, UpdateGroup.class})
private String username;
/**
* 密碼
*/
@NotBlank(message="密碼不能為空", groups = AddGroup.class)
private String password;
/**
* 郵箱
*/
@NotBlank(message="郵箱不能為空", groups = {AddGroup.class, UpdateGroup.class})
@Email(message="郵箱格式不正确", groups = {AddGroup.class, UpdateGroup.class})
private String email;
/**
* 狀态
*/
@NotNull(message="不能為空", groups = {AddGroup.class, UpdateGroup.class})
private Integer status;
}
controller層進行參數判斷:(校驗所抛異常需處理,此處是使用ValidatorUtils.validateEntity中自己定義的處理,另外結合異常處理類)
@PostMapping("/save")
public R save(@RequestBody UserEntity user) {
//此處可以自己寫校驗工具,也可以參考官方文檔
//此處是添加方法故使用UserEntity類中的AddGroup.class
//如果是編輯操作則使用Update.class
//此處也可以不寫**.class,此時對應的實體類中參數校驗注解中也不能寫groups屬性
ValidatorUtils.validateEntity(user, AddGroup.class);
//業務代碼省略
}
注意:對Integer、Long等類型判斷非空時使用@NotNull,對String類型一般使用@NotBlank判斷(空白字元串屬于false)。
同時使用一些注解時,比如@Length、@Email等需要先進行非空判斷,也就是非空判斷的注解寫在目前注解上方即可
對于@NotNull、@NotBlank、@NotEmpty需要注意區分
Hibernate-Validator詳細使用可參考文檔:https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1