在Springboot项目中,我们时常要对从前端传入的domain对象进行验证,检验它是否合法然后再进行后续的操作,这个时候我们就可以使用Springboot自带的验证功能来完成这一操作。
步骤
I. 创建domain类并附上@SomeConstraint
注解:
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
@StudentSearchConstraint
public class Search implements Serializable {
private String name;
private String age;
private String gender;
@NotBlank
private String uniNo;
}
II. 创建Constraint注解:
@Documented
@Constraint(validatedBy = StudentSearchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentSearchConstraint {
String message() default "Error 400 - Uni No. is missing or empty in student search request";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
III. 创建Validator类,用于实现Constraint注解:
package com.schwarzit.dmm.core.validator;
import com.schwarzit.dmm.core.domain.Search;
import java.util.Objects;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;
public class StudentSearchValidator implements ConstraintValidator<SearchConstraint, Student> {
@Override
public boolean isValid(Student student, ConstraintValidatorContext context) {
if (StringUtils.isBlank(student.getUniNo())) {
return false;
}
return hasOneRequiredField(student);
}
private static boolean hasOneRequiredField(Student student) {
return StringUtils.isNotBlank(search.getUniNo()) ||
StringUtils.isNotBlank(search.getName()) ||
StringUtils.isNotBlank(search.getAge()) ||
StringUtils.isNotBlank(search.getGender());
}
}
完成之后,当传入的domain对象不符合要求时程序就会抛出异常。