需求是:webservice传来的数据后台服务器需要进行验证~
我想通过注解在每个ActionForm中的getXXX方法加注解进行验证 ,
但是注解不太怎么会用,请各位高人给个思路,谢谢啦。

解决方案 »

  1.   

    给个例子吧。先我们先定义一个注解,来标识某个属性需要验证
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;/**
     * 
     * @author <a href="mailto:[email protected]">amos zhou</a>
     * @Function:用来标识需要验证
     * @Since Aug 24, 2011
     *
     */
    @Target(ElementType.FIELD)  
    @Retention(RetentionPolicy.RUNTIME) 
    public @interface Validation {}
    2。定义好各种验证 ,这里以长度为例:
    /**
     * 
     * @author <a href="mailto:[email protected]">amos zhou</a>
     * @Function:验证长度
     * @Since Aug 24, 2011
     *
     */
    @Target(ElementType.FIELD)  
    @Retention(RetentionPolicy.RUNTIME) 
    public @interface Length { int minLength();
    int maxLength();
    }3。定义一个枚举,将所有的验证类型名,列出来,如下:
    public enum ValidateType { Required,
    Length,
    Email;

    }
      

  2.   

    4。编写验证方法
    public class Validate { public static <T> boolean validate(T t) throws IllegalArgumentException, IllegalAccessException {
    Class classz = t.getClass();
    Field[] fieldArr = classz.getFields();
    for(Field f : fieldArr){
    Annotation[] anArr = f.getAnnotations();
    List<Annotation> list =  Arrays.asList(anArr);
    if(!list.contains(Validation.class)){
    continue;
    }
    f.setAccessible(true);
    Object fieldValue = f.get(t);
    for(Annotation an : list){
    String typeName = an.annotationType().toString();
    switch(ValidateType.valueOf(typeName)){
    case Length:
    return validateLength(fieldValue.toString(),(Length)an);
    }
    }
    }
    return true;
    }

    public static boolean validateLength(String str,Length length){
    int maxLength = length.maxLength();
    int minLength = length.minLength();
    if(str.length()<minLength){
    return false;
    }
    if(str.length()>maxLength){
    return false;
    }
    return true;
    }
    }当然,你可以这个验证方法,你可以用成员方法来写, 亦可以用多态机制。来完成
        
    我这里以成员方法为例。。这只是一个DEMO,我就不细致优化了。。  另外这个代码可能是运行不通的需要自己调试,仅提供一种思路。
      在使用的时候。。  调用一个方法   boolean resulut = Validate.validate(obj);
      

  3.   

    呵呵,javaee版主亲自给你写的列子,一定没有错了。楼主真是好运,开心吧!
      

  4.   

    对了,甚至你的验证操作都可以不必要自己每次去写用一个aop(spring也好,aspectj也罢),拦截webService相关的返回值