Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Architecture & Framework  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 Jakarta Common Validator笔记
JiafanZhou



版主


发贴: 736
积分: 61
于 2006-09-25 18:03 user profilesend a private message to usersend email to JiafanZhousearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
下面绝对是我的原创的文章,关于Jakarta Common Validator在一个JAVA application里面的运用,也是我的整理笔记。

我敢保证网络上现在还没有同类的文章,有的也是对于Web application的validation.看到是你们赚了阿。

斑竹要加分阿。。。我很用心整理的。而且我不打算在Javaranch上面贴了,不能便宜的老外。(Reference: Jakarta Commons Online bookshel by Vikram Goyal)..

Jakarta Commons Validator notes from Jiafan

---------------------------------------------------------------------
Purpose:
Validator provides a guideline and API for validating user data.
It forces the developer to centralize and streamline data validation
and lays down the best possible way to manage this validation.

At the same time, it provides an API that brings order to data
validation. It really is the tool that you cannot live without,
if your application regularly accepts user data.

---------------------------------------------------------------------
The Validator API:
** org.apache.commons.validator.Validator
** org.apache.commons.validator.util.ValidatorUtils

The Validator class works with two other classes from the same package.

** org.apache.commons.validator.ValidatorResources

1. ValidatorResources, is used to define the rules associated with a
particular set of input data. The individual fields in the input data
are called fields, the set of input data is collectively called a form,
and a collection of forms is called a form-set.

The relationship between the elements is shown here:
Fields --> Forms --> FormSet

Thus, the ValidatorResources class is responsible for making the Validator
class aware of the rules to be applied to a form-set.
Note that this information is sensitive to the current user's locale.

** org.apache.commons.validator.DateValidator
** org.apache.commons.validator.EmailValidator
** org.apache.commons.validator.CreditCardValidator
** org.apache.commons.validator.UrlValidator
** org.apache.commons.validator.GenericValidator
** org.apache.commons.validator.ISBNValidator

2. The other class that Validator works with is, in reality, not one class
but a group of classes. These classes are a set of validation routines
that implement the validation rules.

However, you don't use these classes directly. Standalone applications need
to build a wrapper around these rules to be able to use them.
In this module, we'll create a wrapper class that will
encapsulate most of these rules.

** org.apache.commons.validator.ValidatorResults
The results of validation are stored in the ValidatorResults class,
which contains individual ValidatorResult class instances corresponding
to each field in which the validations were performed.

---------------------------------------------------------------------
The steps of the validation process:

Notice that as far as the Validator component is concerned,
it only needs to validate a Java class that conforms to
the JavaBean syntax.

1. Create or modify a wrapper class around validation rules.
2. Define the validation rules for a targeted data set.
3. Convert or accept user input data as a JavaBean.
4. Create an instance of Validator.
5. Pass in the rules and user data to this instance.
6. Call the validate method of the Validator instance, and accept
results in the ValidatorResults class instance.
7. Process the results.

---------------------------------------------------------------------
Validator API is dependent on several other Commons components:
Commons-Logging http://jakarta.apache.org/commons/logging
Commons-Beanutils http://jakarta.apache.org/commons/beanutils
Commons-Collections http://jakarta.apache.org/commons/collections
Commons-Digester http://jakarta.apache.org/commons/digester
ORO (text-processing Java classes) http://jakarta.apache.org/oro/

---------------------------------------------------------------------
Code example:

1.Building a wrapper class
A wrapper class is a class built around the validation rules that
exercises these rules for your application.

<In this section, we'll create a simple wrapper class.
This wrapper class contains a single method that enforces a
required condition on user data.>


package com.validate;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.util.ValidatorUtils;

public class ValidatorWrapper
{
/**
* Check whether a field in the user form has an empty value or is not present.
*
* @param bean user data represented as a JavaBean
* @param field the Validator components's representation of the field
* in the user data that is to be validated.
* @return true if the value is not null or zero length, false otherwise.
*/
public static boolean doRequired(Object bean, Field field)
{
//
//Get the value of the field as String. The Validator API only
//accepts String values for its built-in validators.
//
String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

//
//examines the String passed in
//
//
return !GenericValidator.isBlankOrNull(value);
}
}


2. Validating a simple JavaBean
As far as Validator is concerned, all user data is in essence
based on JavaBean-style get and set properties.
This way, it's easy to retrieve the value of a property or field in
the user data and validate it according to Validator's rule.

<We create a simple JavaBean that contains two properties, firstName
and lastName, along with their respective get and set methods.
We will validate this simple bean.>


package com.bean;

/**
* This is the JavaBean to validate and act as our user data,
* we need to create the targeted set of validation rules that
* will be applied to this JavaBean.
*/
public class SimpleJavaBeanV1
{
private String firstName;
private String lastName;

public SimpleJavaBeanV1()
{
}

public String getFirstName()
{
return firstName;
}

public void setFirstName(String firstName)
{
this.firstName = firstName;
}

public String getLastName()
{
return lastName;
}

public void setLastName(String lastName)
{
this.lastName = lastName;
}
}


3.Creating targeted validation rules
Creating targeted validation rules means that Validator needs to be
told which method of which class to call to find out whether a
particular field passes a particular validation.

To make this step of the process independent enough that it can be
performed during runtime, Validator allows you to define these rules
in an XML file and not in source code.
(also it can be done in source code as well)

<Creating a targeted set of validation rules in the file
VSimpleJavaBean.xml>

[xml]
<!DOCTYPE form-validation PUBLIC
  "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN"
  "http://jakarta.apache.org/commons/dtds/validator_1_2_0.dtd">

<!--
  1. Validator uses the Digester component from commons to parse
   this xml file. (parsing XML files with Digester requires a set
   of rules for Digester defined in its own XML file.)
  2. only two elements are allowed within root element
   <global> <formset>
-->
<form-validation>
  <global>
    
    <!--
      Define targeted validator.
      
      i.e.
      'required' in com.validate.ValidatorWrapper class
      and the method to call is doRequired() with the
      given parameters.
      
      By putting these values in this XML file, we are
      telling the Validator that in the <formset> elements
      below, if a field needs to be validated to ensure
      that it is present, it can call  this 'required' Validator.
      
      Targeting isn't complete until the field elements to be
      targeted are told which rules to follow done by putting
      the 'required' value in the 'depends' attribute.
      
     -->
     <validator name="required"
           classname="com.validator.ValidatorWrapper"
           method="doRequired"
           methodParams="java.lang.Object, org.apache.commons.validator.Field"
           msg="" />
           
  </global>
  
  <!--
    Define collection of forms
   -->
  <formset>
    <!--
      Define collection of fields.
     -->
    <form name="simpleJavaBean">
      <field property="firstName" depends="required">
      </field>
      
      <field property="lastName" depends="required">
      </field>
    </form>
  </formset>
  
</form-validation>
[/xml]

4. Validating the JavaBean instance.
What we have now currently are following:
--> the wrapper class that contains the methods to be called
for validation.
--> the JavaBean, an instance of which needs to be validated.
--> set of rules that created a mapping between JavaBean properties/fields
and the wrapper class methods.

All we need to do now is create a Validator instance, accept user data,
validate it and process the results.


package com.validator;

import java.io.FileInputStream;

import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.ValidatorResult;
import org.apache.commons.validator.ValidatorResults;

import com.bean.SimpleJavaBean;

public class VSimpleJavaBean
{
public static void main(String[] args) throws Exception
{
//1. load targeted rules.
//This class loads tge rules and uses the Digester component to parse them.
String currentWorkingDirectory = System.getProperty("user.dir");
ValidatorResources resources = new ValidatorResources(
new FileInputStream(currentWorkingDirectory + "\\conf\\validation\\SimpleJavaBean.xml"));

//2. accept user data
Object userData = simulateUserData();

//3. create and initialize new Validator instance
/*
* "simpleJavaBean" is the name of the <form> element in the
* XML file to be processed.
* The same XML file can be used to define the processing of
* several forms.
*/
Validator validator = new Validator(resources, "simpleJavaBean");

/*
* Notice that, if you're doing multiple validations, and each piece
* of user data is represented by a different Javabean instance,
* you'll need to reset this parameter.
*/
validator.setParameter(Validator.BEAN_PARAM, userData);

//4. perform validation
ValidatorResults results = validator.validate();

//5. return results for each field
ValidatorResult result1 = results.getValidatorResult("firstName");
ValidatorResult result2 = results.getValidatorResult("lastName");

//6. Print results for each field's validation
// passed in each field name
System.err.println("First Name: " + result1.isValid("required"));
System.err.println("Last Name: " + result2.isValid("required"));


}

private static Object simulateUserData()
{
SimpleJavaBean bean = new SimpleJavaBean();
bean.setLastName("Zhou");
return bean;
}
}


---------------------------------------------------------------------
Regards,
Jiafan



When I was a kid I used to pray every night for a new bike. Then I realized that The Lord doesn't work that way, so I stole one and asked him to forgive me.

话题树型展开
人气 标题 作者 字数 发贴时间
16282 Jakarta Common Validator笔记 JiafanZhou 11465 2006-09-25 18:03
11281 Re:Jakarta Common Validator笔记 JiafanZhou 66 2006-09-25 18:09
11301 Re:Jakarta Common Validator笔记 JiafanZhou 70 2006-09-27 05:23
11716 Re:Jakarta Common Validator笔记 yeafee 11 2006-12-14 17:43

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923