SpringFramework中的數(shù)據(jù)校驗(yàn)方式
數(shù)據(jù)校驗(yàn)(Validation)
通過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)的屬性,錯誤碼,提示信息
errors.rejectValue("age","age.value.error","age<0")
}else if(p.getAge()>100){
errors.rejectValue("age","age.value.error.old","age>100")
}
}
}測試類
@Test
public void test(){
//創(chuàng)建person對象
Person person = new Person();
person.setName("li");
person.setAge(-1);
//創(chuàng)建person對應(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());
}通過Validation注解
配置類,配置LocalValidatorFactoryBean
@Configuration
@ComponentScan("com.atli")
public class ValidationConfig{
@Bean
public LocalValidatorFactoryBean validator(){
return new LocalValidatorFactoryBean();
}
}實(shí)體類
/**
* 常用注解
* @NotNull:不為空
* @NotEmpty:用于字符串,字符串不為空,長度不為0
* @NotBlank:用于字符串,字符串不為空,trim()后不為空串
* @DecimalMax(value):不大于指定值的數(shù)字
* @DecimalMin(value):不小于指定值的數(shù)字
* @Max(value):不大于指定值數(shù)字
* @Min(value):不小于指定值數(shù)字
* @Pattern(value):符合指定正則表達(dá)式
* @Size(max,min):字符長度在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();
}
}測試類
//測試原生校驗(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);
}
//測試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();
}
}測試類
@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í)是通過自定義注解的方式來擴(kuò)展已有的校驗(yàn)功能以下用校驗(yàn)沒有空格為例
自定義注解(可以直接在已有注解中改)
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy={CannotBlankValidation.class})
public @interface CannotBlank{
//默認(rèn)錯誤提示信息
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 如何解決Could not transfer artifact org.springframework.boot問題
- SpringBoot引入Redis報(bào)org.springframework.data.redis.core.RedisTemplate類找不到錯誤問題
- 程序包org.springframework.boot不存在的問題解決
- java:無法訪問org.springframework.boot.SpringApplication問題
- 程序包org.springframework不存在的解決辦法
- org.springframework.web.client.ResourceAccessException資源訪問錯誤的解決方法
- Java報(bào)錯:Error:java:?程序包org.springframework.boot不存在解決辦法
相關(guān)文章
SpringBoot2 集成log4j2日志框架的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot2 集成log4j2日志框架的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Spring Boot基于數(shù)據(jù)庫如何實(shí)現(xiàn)簡單的分布式鎖
這篇文章主要給大家介紹了關(guān)于Spring Boot基于數(shù)據(jù)庫如何實(shí)現(xiàn)簡單的分布式鎖的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
JavaWeb實(shí)現(xiàn)用戶登錄與注冊功能(服務(wù)器)
這篇文章主要介紹了JavaWeb實(shí)現(xiàn)用戶登錄與注冊功能,服務(wù)器部分的關(guān)鍵代碼實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
Java異常簡介和架構(gòu)_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要分享了Java異常簡介和架構(gòu),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
Java阻塞延遲隊(duì)列DelayQueue原理及使用詳解
這篇文章主要介紹了Java阻塞延遲隊(duì)列DelayQueue原理及使用詳解,阻塞隊(duì)列是一個支持兩個附加操作的隊(duì)列,這兩個附加的操作是:在隊(duì)列為空時,從隊(duì)列中獲取元素的消費(fèi)者線程會一直等待直到隊(duì)列變?yōu)榉强?需要的朋友可以參考下2023-12-12
mybatis mapper.xml獲取insert后的自增ID問題
這篇文章主要介紹了mybatis mapper.xml獲取insert后的自增ID問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
在SpringBoot中通過jasypt進(jìn)行加密解密的方法
今天小編就為大家分享一篇關(guān)于在SpringBoot中通過jasypt進(jìn)行加密解密的方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01

