校验方式二: Spring Validator
Validator接口的实现:
Spring框架的Validator接口定义:
package org.springframework.validation;
public interface Validator {
boolean supports(Class<?> clazz);
void validate(Object target, Errors errors);
}
要使用它进行校验必须实现该接口。实现Validator接口的代码如下:
package org.study.validation.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.study.domain.User;
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(User.class);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "用户名不能为空");
ValidationUtils.rejectIfEmpty(errors, "password", "user.password.required", "密码不能为空");
ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "邮箱不能为空");
User user = (User)target;
int length = user.getUserName().length();
if(length>20){
errors.rejectValue("userName", "user.userName.too_long", "用户名不能超过{20}个字符");
}
length = user.getPassword().length();
if(length <6){
errors.rejectValue("password", "user.password.too_short", "密码太短,不能少于{6}个字符");
}else if(length>20){
errors.rejectValue("password", "user.password.too_long", "密码太长,不能长于{20}个字符");
}
int index = user.getEmail().indexOf("@");
if(index == -1){
errors.rejectValue("email", "user.email.invalid_email", "邮箱格式错误");
}
}
}
设置Validator,并触发校验
在我们的Controller中需要使用父类已有的方法来为DataBinder对象指定Validator, protected initBinder(WebDataBinder binder); 代码如下:
@InitBinder
protected void initBinder(WebDataBinder binder){
binder.setValidator(new UserValidator());
}
为binder对象指定好Validator校验对象后,下面一步的就是在需要校验的时候触发validate方法,该触发步骤是通过 @Validated 注解(该注解是Spring框架定义的)实现的。
/**
* 处理提交的用户注册信息。
* @param model
* @return
*/
@RequestMapping (method = RequestMethod.POST)
public String doRegister(@Validated User user, BindingResult result){
if(logger.isDebugEnabled()){
logger.debug("process url[/user], method[post] in "+getClass());
}
//校验没有通过
if(result.hasErrors()){
return "user";
}
if(user != null){
userService.saveUser(user);
}
return "user";
}
springMVC中两种validation的简单使用
最新推荐文章于 2025-02-16 00:46:01 发布