SpringBoot 時間校驗

2021-09-25 10:38:00 字數 1208 閱讀 4487

在日常開發中常常會出現介面引數中有開始時間和結束時間兩個屬性,需要校驗兩個時間的大小關係,但jsr-303並未給出這樣的註解,但是給出了constraintvalidator這個介面,提供使用者的自定義校驗。下面開始開始時間和結束時間校驗的註解。

1 時間校驗註解

這個註解只能應用於類上,通過starttime和endtime方法指定被註解的類的開始時間和結束時間的屬性名。

@target()

@documented

@retention(retentionpolicy.runtime)

@constraint(validatedby = )

public @inte***ce timevalidate ;

class<? extends payload> payload() default {};

}

2 時間校驗的實現類timevalidate

@slf4j

public class timelimitvalidate implements constraintvalidator

@override

public boolean isvalid(object object, constraintvalidatorcontext constraintvalidatorcontext)

if(starttime instanceof long && (long)starttime > (long) endtime)

if(starttime instanceof date && ((date) starttime).gettime() > ((date)endtime).gettime())

return true;

}/**

* 從object中獲取指定的屬性的值

* @param object

* @param paramname

* @return

* @throws nosuchfieldexception

* @throws illegalacces***ception

*/private object getobjectpropertyvalue (object object, string paramname) catch (exception e)

return null;

}}

Spring Boot 引數校驗

開發過程中,後台的引數校驗是必不可少的,所以經常會看到類似下面這樣的 這樣寫並沒有什麼錯,還挺工整的,只是看起來不是很優雅而已。接下來,用validation來改寫這段 在spring boot的官網中,關於validation只是簡單的提了一句,如下 其實,spring validator和hib...

SpringBoot 引數校驗

採用註解式引數校驗機制 在control物件前新增標籤 valid 在校驗物件字段上面新增 notblank null 限制只能為null notnull 限制必須不為null assertfalse 限制必須為false asserttrue 限制必須為true decimalmax value ...

SpringBoot 資料校驗

新增pom依賴 org.springframework.bootgroupid spring boot starter validationartifactid dependency 編寫實體類 author wsyjlly create 2019.06.29 12 18 allargsconstr...