Validator 接口是Spring框架中用于数据校验的接口,用于定义数据校验逻辑
。在Spring中,数据校验可以通过实现 Validator 接口或使用注解来实现。
Validator接口实现:
- 实现Validator接口:需要
实现 Validator 接口
,并重写supports
方法和validate
方法。 - supports方法:用于指定该校验器支持的
校验类型
。 - validate方法:用于执行具体的
数据校验逻辑
。
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty.user.username");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty.user.password");
// 自定义校验逻辑
if (user.getPassword().length() < 6) {
errors.rejectValue("password", "Size.user.password");
}
}
}
注解实现:
- 使用注解:可以在实体类的字段上添加校验注解,如 @NotNull 、 @Size 等。
- 校验注解:Spring提供了一系列校验注解,如 @NotNull 、 @Size 、 @Email 等,用于定义校验规则。
public class User {
@NotNull
@Size(min = 3, max = 50)
private String username;
@NotNull
@Size(min = 6, max = 20)
private String password;
}
使用方法:
在Spring中,可以将 Validator 接口实现类或带有校验注解的实体类注入到Controller中,然后在Controller中调用校验逻辑进行数据校验。
@Controller
public class UserController {
@Autowired
private UserValidator userValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(userValidator);
}
@PostMapping("/user")
public String addUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
if (result.hasErrors()) {
return "error";
}
// 校验通过,执行业务逻辑
return "success";
}
}
UserValidator 是一个实现了 Validator 接口的校验器, User 类使用注解定义了校验规则。在 UserController 中,通过 @Valid 注解触发数据校验,校验结果会存储在 BindingResult 对象中。