SpringFramework中的數(shù)據(jù)校驗(yàn)方式
數(shù)據(jù)校驗(yàn)(Validation)
通過(guò)Validator接口
引入相關(guān)依賴
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>7.0.5.Final</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>jakarta.el</artifactId> <version>4.0.1</version> </dependency>
實(shí)體類
@Data public class Person{ private String name; private String age; }
數(shù)據(jù)校驗(yàn)器類
public class PersonValidator implements Validator{ //指定需要校驗(yàn)的類型 @Override public boolean supports(Class<?> clazz) { return Person.class.equals(clazz); } //校驗(yàn)規(guī)則 @Override public void validate(Object target, Errors errors) { //name不能為空 ValidationUtils.rejectIfEmpty(errors,"name",errorCode:"name.empty","name is null") //<0age<100 Person p = (Person)target; if(p.getAge()<0){ //參數(shù)依次為,需要校驗(yàn)的屬性,錯(cuò)誤碼,提示信息 errors.rejectValue("age","age.value.error","age<0") }else if(p.getAge()>100){ errors.rejectValue("age","age.value.error.old","age>100") } } }
測(cè)試類
@Test public void test(){ //創(chuàng)建person對(duì)象 Person person = new Person(); person.setName("li"); person.setAge(-1); //創(chuàng)建person對(duì)應(yīng)databinder DataBinder binder = new DataBinder(person); //設(shè)置校驗(yàn)器 binder.setValidator(new PersonValidator()); //調(diào)用方法執(zhí)行校驗(yàn) binder.validate(); //輸出校驗(yàn)結(jié)果 BindingResult result = binder.getBindingResult(); System.out.println(result.getAllErrors()); }
通過(guò)Validation注解
配置類,配置LocalValidatorFactoryBean
@Configuration @ComponentScan("com.atli") public class ValidationConfig{ @Bean public LocalValidatorFactoryBean validator(){ return new LocalValidatorFactoryBean(); } }
實(shí)體類
/** * 常用注解 * @NotNull:不為空 * @NotEmpty:用于字符串,字符串不為空,長(zhǎng)度不為0 * @NotBlank:用于字符串,字符串不為空,trim()后不為空串 * @DecimalMax(value):不大于指定值的數(shù)字 * @DecimalMin(value):不小于指定值的數(shù)字 * @Max(value):不大于指定值數(shù)字 * @Min(value):不小于指定值數(shù)字 * @Pattern(value):符合指定正則表達(dá)式 * @Size(max,min):字符長(zhǎng)度在min到max之間 * @Email:為email格式 */ @Component @Data public class User{ @NotNull private String name; @Min(0) @Max(100) private int age; public User(String name, int age){ this.name=name; this.age=age; } }
校驗(yàn)器
//原生的校驗(yàn)器寫法 @Service public class JavaValidation{ @Autowired private Validator validator; public boolean validatorByUser(User user){ Set<ConstraintViolation<User>> validate=validator.validate(user); return validate.isEmpty(); } } //spring的校驗(yàn)器寫法 @Service public class SpringValidation{ @Autowired private Validator validator; public boolean validatorByUser(User user){ BindException bindException = new BindException(user,user.getName()); validator.validate(user,bindException); return bindException.hasErrors(); } }
測(cè)試類
//測(cè)試原生校驗(yàn)器 @Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class); JavaValidation javaValidation = context.getBean(JavaValidation.class); User user = new User("li",-1); boolean message = javaValidation.validatorByUser(user); System.out.println(message); } //測(cè)試spring校驗(yàn)器 @Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class); SpringValidation springValidation = context.getBean(SpringValidation.class); User user = new User("li",-1); boolean message = springValidation.validatorByUser(user); System.out.println(message); }
基于方法實(shí)現(xiàn)校驗(yàn)
配置類
@Configuration @ComponentScan("com.atli") public class ValidationConfig{ @Bean public MethodValidationPostProcessor validationPostProcessor(){ return new MethodValidationPostProcessor(); } }
實(shí)體類
@Data public class User{ @NotNull private String name; @Min(0) @Max(100) private int age; public User(String name, int age){ this.name=name; this.age=age; } }
校驗(yàn)器
@Service @Validated public class UserService{ public String testMethod(@NotNull @Valid User user){ return user.toString(); } }
測(cè)試類
@Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class); UserService service = context.getBean(UserServicen.class); User user = new User("li",-1); service.testMethod(user); }
自定義校驗(yàn)
自定義校驗(yàn)其實(shí)是通過(guò)自定義注解的方式來(lái)擴(kuò)展已有的校驗(yàn)功能以下用校驗(yàn)沒(méi)有空格為例
自定義注解(可以直接在已有注解中改)
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy={CannotBlankValidation.class}) public @interface CannotBlank{ //默認(rèn)錯(cuò)誤提示信息 String message() default "cannot blank" Class<?>[] groups() default{}; Class<? extends Payload>[] payload() default{}; @Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface List{ NotNull[] value(); } }
注解解析器
public class CannotBlankValidation implements ConstraintValidator<CannotBlank,String>{ @Override public boolean isValid(String value, ConstraintValidatorContext context){ if(value != null && value.contains(" ")){ return false; } } }
到此這篇關(guān)于SpringFramework中的數(shù)據(jù)校驗(yàn)方式的文章就介紹到這了,更多相關(guān)SpringFramework數(shù)據(jù)校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 如何解決Could not transfer artifact org.springframework.boot問(wèn)題
- SpringBoot引入Redis報(bào)org.springframework.data.redis.core.RedisTemplate類找不到錯(cuò)誤問(wèn)題
- 程序包org.springframework.boot不存在的問(wèn)題解決
- java:無(wú)法訪問(wèn)org.springframework.boot.SpringApplication問(wèn)題
- 程序包org.springframework不存在的解決辦法
- org.springframework.web.client.ResourceAccessException資源訪問(wèn)錯(cuò)誤的解決方法
- Java報(bào)錯(cuò):Error:java:?程序包org.springframework.boot不存在解決辦法
相關(guān)文章
SpringBoot2 集成log4j2日志框架的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot2 集成log4j2日志框架的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10Spring Boot基于數(shù)據(jù)庫(kù)如何實(shí)現(xiàn)簡(jiǎn)單的分布式鎖
這篇文章主要給大家介紹了關(guān)于Spring Boot基于數(shù)據(jù)庫(kù)如何實(shí)現(xiàn)簡(jiǎn)單的分布式鎖的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07JavaWeb實(shí)現(xiàn)用戶登錄與注冊(cè)功能(服務(wù)器)
這篇文章主要介紹了JavaWeb實(shí)現(xiàn)用戶登錄與注冊(cè)功能,服務(wù)器部分的關(guān)鍵代碼實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08Java異常簡(jiǎn)介和架構(gòu)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要分享了Java異常簡(jiǎn)介和架構(gòu),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06SpringBoot全局異常處理之解決404/500錯(cuò)誤
在搭建項(xiàng)目框架的時(shí)候用的是springboot,想統(tǒng)一處理異常,但是發(fā)現(xiàn)404的錯(cuò)誤總是捕捉不到,總是返回的是springBoot自帶的錯(cuò)誤結(jié)果信息,這篇文章主要給大家介紹了關(guān)于SpringBoot全局異常處理之解決404/500錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下2023-11-11Java阻塞延遲隊(duì)列DelayQueue原理及使用詳解
這篇文章主要介紹了Java阻塞延遲隊(duì)列DelayQueue原理及使用詳解,阻塞隊(duì)列是一個(gè)支持兩個(gè)附加操作的隊(duì)列,這兩個(gè)附加的操作是:在隊(duì)列為空時(shí),從隊(duì)列中獲取元素的消費(fèi)者線程會(huì)一直等待直到隊(duì)列變?yōu)榉强?需要的朋友可以參考下2023-12-12mybatis mapper.xml獲取insert后的自增ID問(wèn)題
這篇文章主要介紹了mybatis mapper.xml獲取insert后的自增ID問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05在SpringBoot中通過(guò)jasypt進(jìn)行加密解密的方法
今天小編就為大家分享一篇關(guān)于在SpringBoot中通過(guò)jasypt進(jìn)行加密解密的方法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01