需求是:webservice传来的数据后台服务器需要进行验证~
我想通过注解在每个ActionForm中的getXXX方法加注解进行验证 ,
但是注解不太怎么会用,请各位高人给个思路,谢谢啦。
我想通过注解在每个ActionForm中的getXXX方法加注解进行验证 ,
但是注解不太怎么会用,请各位高人给个思路,谢谢啦。
解决方案 »
- java正则表达式验证IP,日期和邮箱格式有效性
- Hibernate中使用oracle数据库失败
- java.net.UnknownHostException和javax.mail.MessagingException的问题
- jsp
- 使用hibernate,对象怎么处理数据字典
- linux下如何通过jdbc访问access数据库文件?
- JSP自动刷新,急。。。
- 关于使用<logic:present role="admin">...</logic:present>的问题
- 初学EJB有一个小小的问题(出现一个不懂的警告)
- 加载不到applicationcontextlistener!
- hibernate疑难(@注解配置实体类映射 )
- hibernate主从表操作问题
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;
}
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);