您的位置:首页 > 编程语言 > Java开发

OVAL 场景验证

2014-03-29 17:18 106 查看
初学OVAL遇到这种情况:

一个User的model,当你登录的时候,你只需要验证用户名和密码字段。当你注册用户的时候你需要验证用户名,密码,邮箱等等。

出现这种情况的时候,不知道该怎么办,也问过一些用过OVAL框架的人,他们说写两个DTO分别来验证。

经过几天的思索,我想到了场景验证,这也是我坐PHP时候用Yii框架时,Yii框架提供的验证规则。

我觉得挺适合这个场景的。也就是说把登录作为一个场景,把注册作为另一个场景,OVAL验证的时候根据场景的不同来验证不同的字段,这样就不需要创建多个DTO。

这里就简单说说我的实现方案(也许OVAL提供了这种问题的解决方案),直接上代码了:

场景验证的注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateScene {
String[] scene();
}



在Model上使用:
@Column(name="username", length=200, unique=false)
private String username;

@Column(name="password", length=200, nullable=false, unique=false)
@NotNull
@Length(max=200)
@ValidateScene(scene={SceneConstants.LOGIN})
private String password;

@Column(name="email", length=200, nullable=false, unique=true)
@NotNull
@Length(max=200)
@Email
@ValidateScene(scene={SceneConstants.LOGIN})
private String email;

自定义一个Validator:

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import net.sf.oval.ConstraintViolation;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.aug.annotation.ValidateScene;
import com.aug.constant.ErrorCodeConstant;
import com.aug.exception.DataWarningException;
import com.aug.exception.ServerErrorException;

@Component(value="validator")
public class Validator extends net.sf.oval.Validator {

private static Logger logger = Logger.getLogger(Validator.class);

public void validate(Class<?> clazz, Object object, String scene)
throws DataWarningException, ServerErrorException {

if (object == null) {
logger.warn(clazz.getName() + "cannot be null.");
throw new DataWarningException(ErrorCodeConstant.VALIDATE_ERROR);
}
List<Field> needValidateField = new ArrayList<Field>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(ValidateScene.class)) {
ValidateScene validateScene = field.getAnnotation(ValidateScene.class);
String[] scenes = validateScene.scene();
for (String sceneStr : scenes) {
if (sceneStr.equals(scene)) {
needValidateField.add(field);
break;
}
}
}
}
StringBuilder sb = new StringBuilder();
boolean isValidatePass = true;
for (Field field : needValidateField) {
field.setAccessible(true);
List<ConstraintViolation> violation = null;
try {
violation = validateFieldValue(
object, field, field.get(object));
} catch (Exception e) {
logger.error(e.getStackTrace(), e);
throw new ServerErrorException(ErrorCodeConstant.SERVER_ERROR);
}
if (violation.size() > 0) {
isValidatePass = false;
for (ConstraintViolation constraintViolation : violation) {
sb.append(constraintViolation.getMessage());
sb.append(",");
}
}
}
if (isValidatePass == false) {
logger.warn("validate error, message is " + sb.toString());
System.out.println(sb.toString());
throw new DataWarningException(ErrorCodeConstant.VALIDATE_ERROR);
}
}

}


在Action中使用Validator:

public String userLogin()
throws DataWarningException, ServerErrorException {

validator.validate(User.class, user, SceneConstants.LOGIN);
userService.userLogin(user, session);
return SUCCESS;
}

思路:

自定义一个Validator继承oval的validator,在这个validator中获取要验证的model的场景注解,然后一个一个的验证。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java OVAL