3、spring 註解驗證@NotNull等使用方法

1、常用的註解

@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(value) 被註釋的元素必須符合指定的正則表達式。
@Email 被註釋的元素必須是電子郵件地址
@Length 被註釋的字符串的大小必須在指定的範圍內
@NotEmpty  被註釋的字符串必須非空
@Range  被註釋的元素必須在合適的範圍內

2、

example :
vo 頁面傳過來的數據進行校驗
inferface : 只是作爲標記一個組別 可以在vo驗證的某個字段上面加入多個組別,這樣沒有加入的組別就不會驗證這個字段
controller: 需要 加入 @Validated (GroupInterface1.class) //GroupInterface1.class是定義的分組 GroupInterface2.class 需要校驗的字段是不會驗證的
原文鏈接:https://blog.csdn.net/qq920447939/article/details/80198438

VO

public class User implements Serializable {
    /**
     * 主鍵
     */
    @NotNull(message = "primary is not null",groups = {GroupInterface1.class})
	private Long id;
	
	@Pattern(regexp = "[0123456789]",groups = {GroupInterface1.class,GroupInterface2.class},message = "hava a error Date")
	private Long maxDiscountAmount;
	

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	private Date createTime;

	@Future(message = "expireTime is not less than now",groups = {GroupInterface1.class,GroupInterface2.class})
	@NotNull(message = "expireTime is not null",groups = {GroupInterface1.class,GroupInterface2.class})
	private Date expireTime;

}

import java.util.Date;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Email;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;

/**** imports ****/
public class ValidatorPojo {

	// 非空判斷
	@NotNull(message = "id不能爲空")
	private Long id;

	@Future(message = "需要一個將來日期") // 只能是將來的日期
	// @Past //只能去過去的日期
	@DateTimeFormat(pattern = "yyyy-MM-dd") // 日期格式化轉換
	@NotNull // 不能爲空
	private Date date;

	@NotNull // 不能爲空
	@DecimalMin(value = "0.1") // 最小值0.1元
	@DecimalMax(value = "10000.00") // 最大值10000元
	private Double doubleValue = null;

	@Min(value = 1, message = "最小值爲1") // 最小值爲1
	@Max(value = 88, message = "最大值爲88") // 最大值88
	@NotNull // 不能爲空
	private Integer integer;

	@Range(min = 1, max = 888, message = "範圍爲1至888") // 限定範圍
	private Long range;

	// 郵箱驗證
	@Email(message = "郵箱格式錯誤")
	private String email;

	@Size(min = 20, max = 30, message = "字符串長度要求20到30之間。")
	private String size;

	

	/**** setter and getter ****/

}

3、此時controller應該要加上@Valid ,否則不會驗證!

	/***
	 * 解析驗證參數錯誤
	 * @param vp —— 需要驗證的POJO,使用註解@Valid 表示驗證
	 * @param errors  錯誤信息,它由Spring MVC通過驗證POJO後自動填充
	 * @return 錯誤信息Map
	 */
	@RequestMapping(value = "/valid/validate")
	@ResponseBody
	public Map<String, Object> validate(
	        @Valid @RequestBody ValidatorPojo vp, Errors errors) {
	    Map<String, Object> errMap = new HashMap<>();
	    // 獲取錯誤列表
	    List<ObjectError> oes = errors.getAllErrors();
	    for (ObjectError oe : oes) {
	        String key = null;
	        String msg = null;
	        // 字段錯誤
	        if (oe instanceof FieldError) {
	            FieldError fe = (FieldError) oe;
	            key = fe.getField();// 獲取錯誤驗證字段名
	        } else {
	            // 非字段錯誤
	            key = oe.getObjectName();// 獲取驗證對象名稱
	        }
	        // 錯誤信息
	        msg = oe.getDefaultMessage();
	        errMap.put(key, msg);
	    }
	    return errMap;
	}

GROUP interface(分組)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章