介绍几种Java对象验证框架_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 介绍几种Java对象验证框架

介绍几种Java对象验证框架

 2012/4/5 13:24:02  wenjinglian  程序员俱乐部  我要评论(0)
  • 摘要:(1)ApacheCommonsValidatorCommons-Validator包用来把验证规则程序提取出来,以供重复使用。这个包可以使用在Struts中,也可以独立的应用在任何其它的应用中。用户可以通过java类的方式自定义验证方法,也可以在配置文件中通过正则表达式配置验证方法。它不但支持服务器端的验证,客户端的验证也支持,具体需要使用tag把相应的js方法写入相应的页面中。配置示例:<form-validation><global><constant>
  • 标签:Java

(1) Apache Commons Validator

?

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

?

配置示例:

?

?

<form-validation>
    <global>
       <constant>
         <constant-name>验证方法的标志名</constant-name>
         <constant-value>正则表达式</constant-value>
       </constant>
       <validator name="这个验证方法的标志名,供下面的depends调用"
                  classname="这个验证方法在哪个类中,为类全名"
                  method="验证方法的名称"
                  methodParams="这个验证方法需要的参数类型,依次以逗号格开,为类全名"
                  depends="基于什么验证之上,可以为多个值,以逗号格开,值为方法的标志名"
                  jsFunction="js的方法全名,格式为文件路径.方法名。文件路径以点隔开,
                              如果不填,默认为org.apache.commons.validator.javascript.xxxx"
                  msg="对应于properties文件中的一条,作为不通过验证时返回的信息"/>
    </global>
    <formset language="语言" country="城市" variant="方言?">
       <constant>
         <constant-name>验证方法的标志名</constant-name>
         <constant-value>正则表达式</constant-value>
       </constant>
       <form name="bean 对象名称">
          <field property="bean中的属性名"   depends="需要什么样的验证,可以为多个值,以逗号格开,值为方法的标志名">
            <arg name = "变量名" key = "properties文件的key,或者来自Var的name" resource = "是/否来自资源文件"/>
            <var>
              <var-name>变量名</var-name>
              <var-value>变量值</var-value>
            </var>
          </field> 
       </form>
    </formset>   
</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更强大,灵活,易于使用。

?

示例:

?

<validation-root namespace="my.project">

  <validation-set id="RegistrationInfoSet" default-resource="theResource">

    <!-- First, let's validate the user's first name. -->
    <use-validator ref="org.iscreen.StringValidator">
      <mapping from="firstName" />
      <label key="label.FirstName" />
      <constraint property="minLength">1</constraint>
      <constraint property="maxLength">25</constraint>
    </use-validator>

    <!-- Now the last name. -->
    <use-validator ref="org.iscreen.StringValidator">
      <mapping from="lastName" />
      <label key="label.LastName" />
      <constraint property="minLength">1</constraint>
      <constraint property="maxLength">30</constraint>
    </use-validator>

    <!-- Make sure that the registration date is after the birthdate. -->
    <use-validator ref="org.iscreen.DateRangeValidator">
      <mapping from="birthDate" to="from" />
      <mapping from="registrationDate" to="to" />
      <label key="label.RegistrationDate" />
      <failure property="failure" key="failure.RegistrationDate" />
    </use-validator>

    <!-- Check the email address. -->
    <use-validator ref="org.iscreen.StringValidator">
      <mapping from="emailAddress" />
      <label key="label.EmailAddress" />
      <constraint property="minLength">1</constraint>
      <constraint property="maxLength">256</constraint>
    </use-validator>

  </validation-set>

  <resource id="theResource">
    <resource-file file="messages" />
  </resource>
</validation-root>

?

?

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

?

?

(3) Java对象验证框架?OVal


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

?

示例:

?

?

private static class TestEntity
{
  @Min(1960)
  private int year = 1977;

  @Range(min=1, max=12)
  private int month = 2;

  @ValidateWithMethod(methodName = "isValidDay", parameterType = int.class)
  private int day = 31;

  private boolean isValidDay(int day)
  {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setLenient(false);
    cal.set(GregorianCalendar.YEAR, year); 
    cal.set(GregorianCalendar.MONTH, month - 1);
    cal.set(GregorianCalendar.DATE, day);
    try {
      cal.getTimeInMillis(); // throws IllegalArgumentException
    } catch (IllegalArgumentException e) { 
      return false;
    }
    return true;
  }
}

?

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应用程序

?

示例:

?

package org.javalid.examples.core.example01;
 
import org.javalid.annotations.core.JvGroup;
import org.javalid.annotations.core.ValidateDefinition;
import org.javalid.annotations.validation.MinLength;
import org.javalid.annotations.validation.NotEmpty;
import org.javalid.annotations.validation.NotNull;
 
@ValidateDefinition
public class Employee {
 
  private String firstName;
  private String lastName;
 
  public Employee() {
  }
 
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
 
  @JvGroup (groups={"group01"})
  @NotNull
  public String getFirstName() {
    return firstName;
  }
 
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
 
  @JvGroup (groups={"group01"})
  @NotEmpty
  @MinLength (length=4)
  public String getLastName() {
    return lastName;
  }
 
}
?

?

import java.util.List;
 
import org.javalid.core.AnnotationValidator;
import org.javalid.core.AnnotationValidatorImpl;
import org.javalid.core.ValidationMessage;
 
public class Test {
 
  public Test() {
  }
 
  public static void main(String[] args) {
    AnnotationValidator validator    = null;
    List<validationmessage> messages = null;
    Employee emp = null;
 
      // Creates a default core validator using default configuration
    validator = new AnnotationValidatorImpl(); 
 
      // Create our employee, as valid (no errors should be found)
    emp = new Employee();
    emp.setFirstName("Martijn");
    emp.setLastName("Reuvers");
 
      // Validate our employee
    messages = validator.validateObject(emp,"group01");
    System.out.println("Employee errors=" + messages.size()); // Should print 0
 
      // Make our employee invalid
    emp.setFirstName(null); // NotNull should get fired
    messages = validator.validateObject(emp,"group01");
    System.out.println("Employee errors=" + messages.size()); // Should print 1
    System.out.println("Message=" + messages.get(0)); // Should print a NotNull message error
 
      // Make our employee even more invalid
    emp.setLastName("");
    messages = validator.validateObject(emp,"group01");
    System.out.println("Employee errors=" + messages.size()); // Should print 2
    System.out.println("Messages=" + messages); // Should print a NotNull / NotEmpty message error    
 
      // Set firstName fine, lastName too short length but not empty
    emp.setFirstName("Martijn");
    emp.setLastName("Re");
    messages = validator.validateObject(emp,"group01");
    System.out.println("Employee errors=" + messages.size()); // Should print 1
    System.out.println("Messages=" + messages); // Should print a MinLength message error        
 
      // Finally, wrong group specified, validates nothing, as its not in the @JvGroup anywhere
    messages = validator.validateObject(emp,"invalidGroup");
    System.out.println("Employee errors=" + messages.size()); // Should print 0
  }
 
}
?

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

?

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

?

?

个人认为大型的网站还是要使用配置的形式,统一管理验证规则。

?

不知道还有没有其它好的后台验证方式。

?

?

?

?

上一篇: 坦克大战总结 下一篇: java枚举类型
发表评论
用户名: 匿名