java几种对象验证框架

(1) Apache Commons Validator

 

Commons -Validator包用来把验证规则程序提取出来,以供重复使用。这个包可以使用在Struts中,也可以独立的应用在任何其它的应用中。用户可以通过 java类的方式自定义验证方法,也可以在配置文件中通过正则表达式配置验证方法。它不但支持服务器端的验证,客户端的验证也支持,具体需要使用tag把 相应的js方法写入相应的页面中。

配置示例:

 

 

Java代码   收藏代码
  1. <form-validation>  
  2.     <global>  
  3.        <constant>  
  4.          <constant-name>验证方法的标志名</constant-name>  
  5.          <constant-value>正则表达式</constant-value>  
  6.        </constant>  
  7.        <validator name="这个验证方法的标志名,供下面的depends调用"  
  8.                   classname="这个验证方法在哪个类中,为类全名"  
  9.                   method="验证方法的名称"  
  10.                   methodParams="这个验证方法需要的参数类型,依次以逗号格开,为类全名"  
  11.                   depends="基于什么验证之上,可以为多个值,以逗号格开,值为方法的标志名"  
  12.                   jsFunction="js的方法全名,格式为文件路径.方法名。文件路径以点隔开,  
  13.                               如果不填,默认为org.apache.commons.validator.javascript.xxxx"  
  14.                   msg="对应于properties文件中的一条,作为不通过验证时返回的信息"/>  
  15.     </global>  
  16.     <formset language="语言" country="城市" variant="方言?">  
  17.        <constant>  
  18.          <constant-name>验证方法的标志名</constant-name>  
  19.          <constant-value>正则表达式</constant-value>  
  20.        </constant>  
  21.        <form name="bean 对象名称">  
  22.           <field property="bean中的属性名"   depends="需要什么样的验证,可以为多个值,以逗号格开,值为方法的标志名">  
  23.             <arg name = "变量名" key = "properties文件的key,或者来自Var的name" resource = "是/否来自资源文件"/>  
  24.             <var>  
  25.               <var-name>变量名</var-name>  
  26.               <var-value>变量值</var-value>  
  27.             </var>  
  28.           </field>   
  29.        </form>  
  30.     </formset>     
  31. </form-validation>   

 

 

官方地址:http://commons.apache.org/validator/index.html

 

 参考:http://hi.baidu.com/pengwx/blog/item/db85b84b33d785f183025ce8.html

(2) iScreen


iScreen是一个Java对象验证框架。它的思想与Apache Jakarta的commons-validator项目相似,验证规则使用XML进行配置但也支持其它配置类型。它比commons-validator更强大,灵活,易于使用。

 

示例:

 

Java代码   收藏代码
  1. <validation-root namespace="my.project">  
  2.   
  3.   <validation-set id="RegistrationInfoSet" default-resource="theResource">  
  4.   
  5.     <!-- First, let's validate the user's first name. -->  
  6.     <use-validator ref="org.iscreen.StringValidator">  
  7.       <mapping from="firstName" />  
  8.       <label key="label.FirstName" />  
  9.       <constraint property="minLength">1</constraint>  
  10.       <constraint property="maxLength">25</constraint>  
  11.     </use-validator>  
  12.   
  13.     <!-- Now the last name. -->  
  14.     <use-validator ref="org.iscreen.StringValidator">  
  15.       <mapping from="lastName" />  
  16.       <label key="label.LastName" />  
  17.       <constraint property="minLength">1</constraint>  
  18.       <constraint property="maxLength">30</constraint>  
  19.     </use-validator>  
  20.   
  21.     <!-- Make sure that the registration date is after the birthdate. -->  
  22.     <use-validator ref="org.iscreen.DateRangeValidator">  
  23.       <mapping from="birthDate" to="from" />  
  24.       <mapping from="registrationDate" to="to" />  
  25.       <label key="label.RegistrationDate" />  
  26.       <failure property="failure" key="failure.RegistrationDate" />  
  27.     </use-validator>  
  28.   
  29.     <!-- Check the email address. -->  
  30.     <use-validator ref="org.iscreen.StringValidator">  
  31.       <mapping from="emailAddress" />  
  32.       <label key="label.EmailAddress" />  
  33.       <constraint property="minLength">1</constraint>  
  34.       <constraint property="maxLength">256</constraint>  
  35.     </use-validator>  
  36.   
  37.   </validation-set>  
  38.   
  39.   <resource id="theResource">  
  40.     <resource-file file="messages" />  
  41.   </resource>  
  42. </validation-root>  

 

 

官方:http://i-screen.org/docs/index.html

 

 

(3) Java对象验证框架 OVal


OVal 是一个可扩展的Java对象数据验证框架,验证的规则可以通过配置文件、Annotation、POJOs 进行设定。可以使用纯 Java 语言、JavaScript 、Groovy 、BeanShell 等进行规则的编写。

 

示例:

 

 

Java代码   收藏代码
  1. private static class TestEntity  
  2. {  
  3.   @Min(1960)  
  4.   private int year = 1977;  
  5.   
  6.   @Range(min=1, max=12)  
  7.   private int month = 2;  
  8.   
  9.   @ValidateWithMethod(methodName = "isValidDay", parameterType = int.class)  
  10.   private int day = 31;  
  11.   
  12.   private boolean isValidDay(int day)  
  13.   {  
  14.     GregorianCalendar cal = new GregorianCalendar();  
  15.     cal.setLenient(false);  
  16.     cal.set(GregorianCalendar.YEAR, year);   
  17.     cal.set(GregorianCalendar.MONTH, month - 1);  
  18.     cal.set(GregorianCalendar.DATE, day);  
  19.     try {  
  20.       cal.getTimeInMillis(); // throws IllegalArgumentException  
  21.     } catch (IllegalArgumentException e) {   
  22.       return false;  
  23.     }  
  24.     return true;  
  25.   }  
  26. }  

 

OVal使用者
The following projects are using OVal:

eSciDoc

https://www.escidoc.org/

SaferJava

http://code.google.com/p/saferjava/

Pinky

https://github.com/pk11/pinky

JProvocateur

http://www.jprovocateur.org/

NexOpen

http://nexopen.sourceforge.net/

gdv.xport

http://repository.agentes.de/gdv/gdv-xport/site/

suz-lab-gae

http://code.google.com/p/suz-lab-gae/

Cubby Simple Web Application Framework

http://cubby.seasar.org/20x/cubby-oval/index.html

Metawidget

http://metawidget.org

Struts 2 OVal Plug-in

http://cwiki.apache.org/confluence/display/S2PLUGINS/OVal+Plugin

Play! Framework

http://www.playframework.org/

Cayenne annotations

http://sourceforge.net/projects/cayannotations/

jsfatwork

http://code.google.com/p/jsfatwork/

mtn4java

http://www.mvnrepository.com/artifact/org.criticalsection.mtn4java/mtn4java/

Polyforms

http://code.google.com/p/polyforms/

rsser

http://code.google.com/p/rsser/

saetc

http://code.google.com/p/saetc/

ultimate-roundtrip

http://code.google.com/p/ultimate-roundtrip/

 

官方:http://oval.sourceforge.net/

 

(4) JaValid

 

JaValid是一个基于标注的验证框架,它允许用户标注Java类来引入验证。JaValid可以应用于任何类型的Java应用程序

 

示例:

 

Java代码   收藏代码
  1. package org.javalid.examples.core.example01;  
  2.    
  3. import org.javalid.annotations.core.JvGroup;  
  4. import org.javalid.annotations.core.ValidateDefinition;  
  5. import org.javalid.annotations.validation.MinLength;  
  6. import org.javalid.annotations.validation.NotEmpty;  
  7. import org.javalid.annotations.validation.NotNull;  
  8.    
  9. @ValidateDefinition  
  10. public class Employee {  
  11.    
  12.   private String firstName;  
  13.   private String lastName;  
  14.    
  15.   public Employee() {  
  16.   }  
  17.    
  18.   public void setFirstName(String firstName) {  
  19.     this.firstName = firstName;  
  20.   }  
  21.    
  22.   @JvGroup (groups={"group01"})  
  23.   @NotNull  
  24.   public String getFirstName() {  
  25.     return firstName;  
  26.   }  
  27.    
  28.   public void setLastName(String lastName) {  
  29.     this.lastName = lastName;  
  30.   }  
  31.    
  32.   @JvGroup (groups={"group01"})  
  33.   @NotEmpty  
  34.   @MinLength (length=4)  
  35.   public String getLastName() {  
  36.     return lastName;  
  37.   }  
  38.    
  39. }  
 

 

Java代码   收藏代码
  1. import java.util.List;  
  2.    
  3. import org.javalid.core.AnnotationValidator;  
  4. import org.javalid.core.AnnotationValidatorImpl;  
  5. import org.javalid.core.ValidationMessage;  
  6.    
  7. public class Test {  
  8.    
  9.   public Test() {  
  10.   }  
  11.    
  12.   public static void main(String[] args) {  
  13.     AnnotationValidator validator    = null;  
  14.     List<validationmessage> messages = null;  
  15.     Employee emp = null;  
  16.    
  17.       // Creates a default core validator using default configuration  
  18.     validator = new AnnotationValidatorImpl();   
  19.    
  20.       // Create our employee, as valid (no errors should be found)  
  21.     emp = new Employee();  
  22.     emp.setFirstName("Martijn");  
  23.     emp.setLastName("Reuvers");  
  24.    
  25.       // Validate our employee  
  26.     messages = validator.validateObject(emp,"group01");  
  27.     System.out.println("Employee errors=" + messages.size()); // Should print 0  
  28.    
  29.       // Make our employee invalid  
  30.     emp.setFirstName(null); // NotNull should get fired  
  31.     messages = validator.validateObject(emp,"group01");  
  32.     System.out.println("Employee errors=" + messages.size()); // Should print 1  
  33.     System.out.println("Message=" + messages.get(0)); // Should print a NotNull message error  
  34.    
  35.       // Make our employee even more invalid  
  36.     emp.setLastName("");  
  37.     messages = validator.validateObject(emp,"group01");  
  38.     System.out.println("Employee errors=" + messages.size()); // Should print 2  
  39.     System.out.println("Messages=" + messages); // Should print a NotNull / NotEmpty message error      
  40.    
  41.       // Set firstName fine, lastName too short length but not empty  
  42.     emp.setFirstName("Martijn");  
  43.     emp.setLastName("Re");  
  44.     messages = validator.validateObject(emp,"group01");  
  45.     System.out.println("Employee errors=" + messages.size()); // Should print 1  
  46.     System.out.println("Messages=" + messages); // Should print a MinLength message error          
  47.    
  48.       // Finally, wrong group specified, validates nothing, as its not in the @JvGroup anywhere  
  49.     messages = validator.validateObject(emp,"invalidGroup");  
  50.     System.out.println("Employee errors=" + messages.size()); // Should print 0  
  51.   }  
  52.    
  53. }  
 

这个相对功能少些,好像目前不支持配置,纯注解。

 

官方: http://www.javalid.org/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值