Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

6.7. 校驗器(Validator)

常見的校驗註解

	
@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提供的校驗註解:
@NotBlank(message =) 驗證字元串非null,且長度必須大於0
@Email 被註釋的元素必須是電子郵箱地址
@Length(min=,max=) 被註釋的字元串的大小必須在指定的範圍內
@NotEmpty 被註釋的字元串的必須非空
@Range(min=,max=,message=) 被註釋的元素必須在合適的範圍內	
	
	

6.7.1. 常規用法

6.7.1.1. 定義校驗器

		
package web.domain;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

	private Long id;

	@NotNull(message = "用戶賬號不能為空")
	@Size(min = 6, max = 11, message = "賬號長度必須是6-11個字元")
	private String username;

	@NotNull(message = "用戶密碼不能為空")
	@Size(min = 6, max = 8, message = "密碼長度必須是6-8個字元")
	private String password;

	@NotNull(message = "用戶郵箱不能為空")
	@Email(message = "郵箱格式不正確")
	private String email;

	// 不允許為空,並且年齡的最小值為18
	@NotNull
	@Min(18)
	private Integer age;

	public User() {
		// TODO Auto-generated constructor stub
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	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 getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", age=" + age + "]";
	}

}
		
		
			

6.7.1.2. 獲取 BindingResult 結果

		
package web.restful;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import web.domain.User;

@RestController
@RequestMapping("/restful")
public class TestRestController {

	@RequestMapping("/test")
	public String home() {
		return "OK";
	}

	@PostMapping("/validation")
	public String addUser(@RequestBody @Valid User user, BindingResult bindingResult) {
		// 如果有參數校驗失敗,返回錯誤信息
		if (bindingResult.hasErrors()) {
			System.out.println(user.toString());
			System.out.println(bindingResult.getErrorCount());
			System.out.println(bindingResult.getAllErrors());
		}

		for (ObjectError error : bindingResult.getAllErrors()) {
			return error.getDefaultMessage();
		}
		return user.toString();
	}

}
		
		
			

6.7.1.3. 測試校驗效果

			
neo@MacBook-Pro-Neo ~/workspace/Management % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkillermsn.com"}' curl http://localhost:8080/restful/validation
郵箱格式不正確

neo@MacBook-Pro-Neo ~/workspace/Management % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com"}' curl http://localhost:8080/restful/validation
must not be null

neo@MacBook-Pro-Neo ~/workspace/Management % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com", "age":20}' curl http://localhost:8080/restful/validation
User [id=100000, username=netkiller, password=123456, email=netkiller@msn.com, age=20]
			
			

6.7.2. 自定義註解

下面實現一個手機號碼檢查的註解。

		
@Retention :用來說明該註解類的生命周期。它有以下三個參數:
RetentionPolicy.SOURCE : 註解只保留在源檔案中
RetentionPolicy.CLASS : 註解保留在class檔案中,在加載到JVM虛擬機時丟棄
RetentionPolicy.RUNTIME : 註解保留在程序運行期間,此時可以通過反射獲得定義在某個類上的所有註解。

@Target : 用來說明該註解可以被聲明在那些元素之前。
ElementType.TYPE:說明該註解只能被聲明在一個類前。
ElementType.FIELD:說明該註解只能被聲明在一個類的欄位前。
ElementType.METHOD:說明該註解只能被聲明在一個類的方法前。
ElementType.PARAMETER:說明該註解只能被聲明在一個方法參數前。
ElementType.CONSTRUCTOR:說明該註解只能聲明在一個類的構造方法前。
ElementType.LOCAL_VARIABLE:說明該註解只能聲明在一個局部變數前。
ElementType.ANNOTATION_TYPE:說明該註解只能聲明在一個註解類型前。
ElementType.PACKAGE:說明該註解只能聲明在一個包名前。

@Constraint來限定自定義註解的方法
		
		

6.7.2.1. 定義校驗器註解介面

			
package cn.netkiller.web.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;

import javax.validation.Constraint;
import javax.validation.Payload;

import cn.netkiller.web.annotation.impl.MobileValidator;

@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MobileValidator.class)
@Documented
// 註解的實現類。
public @interface Mobile {
	// 校驗錯誤的預設信息
	String message() default "手機號碼格式不正確!";

	// 是否強制校驗
	boolean isRequired() default true;

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};
}
			
			

6.7.2.2. 實現介面

			
package cn.netkiller.web.annotation.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.util.StringUtils;

import cn.netkiller.web.annotation.Mobile;

public class MobileValidator implements ConstraintValidator<Mobile, String> {

	public MobileValidator() {
		// TODO Auto-generated constructor stub
	}

	private boolean required = false;

	@Override
	public void initialize(Mobile constraintAnnotation) {
		required = constraintAnnotation.isRequired();
	}

	@Override
	public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
		Pattern mobile_pattern = Pattern.compile("1\\d{10}");
		// System.out.println(phone);
		// 是否為手機號的實現
		if (required) {
			if (StringUtils.isEmpty(phone)) {
				return false;
			}
			Matcher m = mobile_pattern.matcher(phone);
			return m.matches();

		} else {
			return StringUtils.isEmpty(phone);
		}
	}
}			
			
			

6.7.2.3. 註解用法

			
package cn.netkiller.web.domain;

import java.util.Date;

import javax.validation.constraints.Email;
import javax.validation.constraints.Future;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import cn.netkiller.web.annotation.Mobile;

public class User {

	private Long id;

	@NotNull(message = "用戶賬號不能為空")
	@Size(min = 6, max = 11, message = "賬號長度必須是6-11個字元")
	private String username;

	@NotNull(message = "用戶密碼不能為空")
	@Size(min = 6, max = 8, message = "密碼長度必須是6-8個字元")
	private String password;

	@NotNull(message = "用戶郵箱不能為空")
	@Email(message = "郵箱格式不正確")
	private String email;

	// 這裡是新添加的註解奧
	@Mobile(message = "手機號碼格式錯誤!!!")
	private String phone;

	// 不允許為空,並且年齡的最小值為18
	@NotNull
	@Min(18)
	private Integer age;

	@Future
	private Date createTime;

	public User() {
		// TODO Auto-generated constructor stub
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	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 getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", phone=" + phone + ", age=" + age + "]";
	}

}			
			
			

6.7.2.4. 測試註解

			
neo@MacBook-Pro-Neo ~ % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com", "age":20, "phone":"BB"}' curl http://localhost:8080/restful/validation
手機號碼格式錯誤!!!

neo@MacBook-Pro-Neo ~ % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com", "age":20, "phone":"2433"}' curl http://localhost:8080/restful/validation
手機號碼格式錯誤!!!

neo@MacBook-Pro-Neo ~ % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com", "age":20, "phone":"130"}' curl http://localhost:8080/restful/validation
手機號碼格式錯誤!!!% 


neo@MacBook-Pro-Neo ~ % curl -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com", "age":20, "phone":"13022223333"}' curl http://localhost:8080/restful/validation
User [id=100000, username=netkiller, password=123456, email=netkiller@msn.com, phone=13022223333, age=20]%