Struts (Commons-validator) source code

Source: Internet
Author: User
Commons-validator (1)

The commons-validator package is used to extract the validation rule program for reuse. This package can be used in struts or independently applied in any other application. You can customize the verification method using Java classes, or configure the verification method using regular expressions in the configuration file. It not only supports server-side verification, but also supports client-side verification. You need to use tags to write the corresponding js method into the corresponding page.

I. Summary:
The entire validator framework can have several formsets, and each FormSet can have several forms, and each form can have several fields. FormSet process (...) method. Call the process (...) of the form one by one (...) and form process (...) the method calls the process (...) of the field one by one (...) method. As the verification start point, the validator class calls the validate (...) of the one-to-one corresponding form (...) method, while form's validate (...) the method calls the field's validate (...) one by one (...) method.

Ii. configuration file description:

<Form-validation>
<Global>
<Constant>
<Constant-Name> Verification Method flag </Constant-Name>
<Constant-value> Regular Expression </Constant-value>
</Constant>
<Validator name = "the flag name of this verification method for the following depends call"
Classname = "in which class this verification method belongs, It is the full name of the class"
Method = "Name of the Verification Method"
Methodparams = "the parameter types required for this verification method are separated by commas (,), which is the full name of the class"
Depends = "based on what verification, you can open multiple values in a comma, and the value is the flag name of the method"
Jsfunction = "full name of the js method, in the format of file path. method name. File paths are separated by dots,
If this parameter is not specified, the default value is org. Apache. commons. validator. Javascript. xxxx"
MSG = "corresponds to one of the properties files, which is returned when verification fails"/>
</Global>
<FormSet Language = "language" Country = "city" variant = "dialect? ">
<Constant>
<Constant-Name> Verification Method flag </Constant-Name>
<Constant-value> Regular Expression </Constant-value>
</Constant>
<Form name = "bean Object Name">
<Field property = "attribute name in bean" depends = "the identifier of a method that can contain multiple values separated by commas (,).">
<Arg name = "variable name" Key = "properties file key, or name from Var" resource = "yes/no from resource file"/>
<Var>
<Var-Name> variable name </var-Name>
<Var-value> variable value </var-value>
</Var>
</Field>
</Form>
</FormSet>
</Form-validation>

Commons-validator (2)

In the validator configuration file, there are several basic elements.

1. org. Apache. commons. validator. var
It provides available variables for other labels in the configuration file (validator. XML) and other parameter values required for field verification, such as the maximum length. This class has the following attributes: name, variable name, value, variable value, and jstype: JS type to be automatically generated.

2. org. Apache. commons. validator. ARG
It is used to replace a part of the information or provide the required parameter values for the verification method. This class has the following attributes: bundle, resource file name, used to store the required information. Key, indicating the key or value of Arg. Name indicates the ARG name. Position. The value in Arg is used to replace the part of the information. The part to be replaced is marked as {n. Resource: whether the information specified by the key comes from an external resource file. The default value is true. If the value is true, the key indicates the key in the resource file specified by the buddle attribute.

Org. Apache. commons. validator. msg
It is used to return information about what should be returned when verification fails. This class has the following attributes: bundle, resource file name, used to store the required information. Key, indicating the key or value of MSG. Name, indicating the MSG name. Resource: whether the information specified by the key comes from an external resource file. The default value is true. If the value is true, the key indicates the key in the resource file specified by the buddle attribute.

4. org. Apache. commons. validator. FormSet
This class is used to manage all form objects to be verified by a map, with the key being the form name. At the same time, a map is used to manage the constant defined in <FormSet/>, the key is <constant-Name>. At the same time, it has the following attributes: language, country, and variant, which are used for internationalization. A configuration file can have multiple formsets. The difference between these formsets is that different localization is required.

5. org. Apache. commons. validator. Form
This class has the following attributes: name, the name of this form. Lfields: a list that stores all fields. Hfields: A fasthashmap that stores all fields. The key value of this fasthashmap corresponds to the key attribute of the field (corresponding to the property in the configuration file ). This class uses the validate (...) method to verify all fields in the form that are less than the page. It actually calls the validate (...) method of each field one by one in a loop, and then saves the result in a validatorresults object.

6. org. Apache. commons. validator. Field
This class has the following attributes: Depends, which validation rules depend on. Dependencylist stores the list generated by separating depends with commas. Page. If it is submitted in multiple steps, the current status is the first step. The value is equal to or less than the page Value in the form, and the JavaBean will be processed. ARGs is an array; the element of this array is hashmap. The position of each hashmap in the array is the value of the position attribute in ARG; the key value in hashmap is the name of Arg, if this name is null, the default value is default_arg (Org. apache. commons. validator. field. default), value is the ARG object. Hvars is a fasthashmap used to manage all var objects. The key is the name of VaR and the value is the VaR object. Getindexedlistproperty indicates that this property is the index of an array element in the JavaBean.

1. Process (MAP globalconstants, map constants)
This method is used to replace variables in the configuration file. Its two parameters are the constant defined in <global/> and <FormSet/> respectively. In this map, the key is the constant-name in the <constant/> label, and the value is <constant-value>. In the configuration file, you can use the following variables: Form's property attribute, Value Attribute IN VaR, key attribute in Arg, and MSG's key attribute, they can reference the constant defined in the <global/> or <FormSet/> label by using the {constant-name} method. The key attribute in Arg can reference the VaR defined in <var/> by using {var: var-name.

Process (...) in FormSet (...) the method calls the process (...) of the Form in sequence (...) and form process (...) the method calls the process (...) of the field in sequence (...) method.

2. Validate (MAP Params, map Actions)
Perform the verification. Actions saves all the validatemedition objects. It first retrieves the value of the key validator. bean_param (Java. Lang. Object) from Params as the JavaBean to be verified. Then, the generatekey () method is used to determine whether the field to be verified is indexedlist. If yes, verify the elements in the list separately. Otherwise, verify the attributes of the JavaBean directly.

3. validateforrule (...)
While accepting the validatemedition object to be executed, the map actions parameter is still accepted because the validatemedition to be executed may depend on other validatations. It first looks for the previous verification results. If this verification has not been performed before, run rundependentvalidators (...) method to execute the validatemedition on which it depends. If it passes, verify the validatemedition to be executed.

Commons-validator (3)

Some util classes are provided in the validator package, and verification methods are provided for basic data types, time, e-mail, credit card, and other formats.

1. org. Apache. commons. validator. util. flags
This class is used to manage a series of flags. The value of each flags is the Npower of 2. Then the bitwise AND (&) between each flag gets the value of the entire flags.

2. org. Apache. commons. validator. util. validatorutils
This class provides some utility operations for validator. There are three methods in total.

1. Replace (...)
This method is used to replace a character string in one string with another. Note that this is a global replacement method.

2. getvalueasstring (...)
This method is used to obtain a specific attribute in a bean and convert the attribute value to a string for return. Note: Values of the string [] and Collection types are returned directly if they do not contain any value "".

3. copyfasthashmap (...)
Obviously, copy is executed on a specific fashhashmap. Note that if the value is of the MSG, ARG, and VAR type, you need to execute clone and save it.

Org. Apache. commons. validator. validatorutil
This class implements its own method of the same name by calling the validatorutils method above. The getdelimitedregexp (...) method is used to generate a regular expression.

4. org. Apache. commons. validator. datevalidator
The Singleton mode is implemented. This class is used to check whether the date type is valid. The date type must be passed to the validator parameter. There is also a strict attribute, indicating the date format required for checking the transition matching. This date check is thrown when an exception occurs during the formatter. parse (value) method check.

5. org. Apache. commons. validator. emailvalidator
The Singleton mode is implemented. This class is used to check whether the email type is valid. It is verified by a regular expression.

6. org. Apache. commons. validator. generictypevalidator
This class detects the basic types (byte, short, Int, long, float, date). The method is very simple, that is, to create an object through each type of constructor, if an exception is thrown, it indicates non-conformity; otherwise, it indicates yes. At the same time, this class also provides the implementation of creditcard verification.

Commons-validator (4)

Start verification by calling validator's validate (...) method.

1. org. Apache. commons. validator. validator
This class is the starting point for performing verification on a form. It starts verification by calling the validate (...) method of this class. The formname attribute in this class corresponds to the name attribute in form. Resources attribute to record which validator belongs. Parameters is used to manage the parameters required to execute the validatexxx (...) method. It is a map, the key is the full name of the class, and the value is an object of the class referred to by the full name of the class. Note that this parameters is the set of parameters required for all fields in the form to execute the validatexxx (...) method. For each validatexxx (...) method, retrieve the parameters you need from the parameters according to the parameter name (full name of the class.

2. org. Apache. commons. validator. validattion tion
Each validatemedition corresponds to a <validator/> in the configuration file. It has the following attributes: name, the name of the positive verification action, which is used in the configuration of the depends attribute. Classname, in which class the verification method belongs, is the full name of the class. Validationclass, a class generated by classname. Method. Validationmethod: The method generated by the method. Methodparams: The parameter required for executing this verification method. The value is the full name of the class separated by commas. The default value is validator. bean_param, validator. validator_action_param, and validator. field_param. Parameterclasses: Class array generated by methodparams. Depends depends on he validatadtion. MSG. If the verification fails, what message should be returned. Javascript: the code content of the corresponding JavaScript method. Jsfunction, which is the name of the corresponding JS file. Jsfunctionname, the name of the method in the corresponding Js.

1. executevalidationmethod (...)
This method detects values in the field. It actually performs the corresponding verification method based on the class name, method name, and parameter type through reflection. Note that if this field is of the indexlist type, you need to replace Java Bean with the elements specified by POS in the corresponding array. [] In the key attribute of field must be changed to [POS].

2. This class also provides basic operations on JS, which are explained as follows:
* Generatejsfunction ()
Generate a JS file name named org. Apache. commons. validator. Javascript. validatexxxx. XXXX corresponds to name.

* Readjavascriptfile (...)
Used to read JS files. Because a JS file contains only one method, it will read all the content and directly return all the read content.

Org. Apache. commons. validator. validatorresults
This class manages the results of verification on all fields in a form. It has the following attributes: hresults, used to manage the results of all field verification. Its key is the Kye attribute of the field, and its value is the validatorresult object.

4. org. Apache. commons. validator. validatorresult
This class is used to manage the results of all verification methods when a field is verified. It has the following attributes: field, the field object to be verified. Haction is used to save the map of all verification results. Its key is the name attribute in validatemedition, and value is the resultstatus object.

5. org. Apache. commons. validator. resultstatus
It encapsulates the results of performing a verification on a field. It has the following attributes: Valid, indicating whether verification is successful. Result: The result after verification.

Commons-validator (5)

Finally, it describes how validator is initialized.

1. org. Apache. commons. validator. validatorresourcesinitializer
This class is used to initialize the validator framework and parse the custom xml configuration file through the digester package. Save the parsed result to the validatorresources object, and return the validatorresources object.

2. org. Apache. commons. validator. validatorresources
This class is used to manage resources in the validator framework. It contains the following attributes: hformsets, A fasthashmap, used to manage all formsets. The key of this fasthashmap is generated according to the local information in the FormSet. Hconstants, A fasthashmap, is used to manage the constant defined in <global/>. Hactions, A fasthashmap, is used to manage validatemedition. Its key is the name attribute of validatemedition.

Iii. configuration to be added when integrating with Struts:
Add in the struts-config.xml file:

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
    </plug-in>

Among them, the validator-rules.xml, for the struts built-in configuration file, configured all the verification methods; and validation. XML for the user's own configuration, configure the object to be verified.

4. org. Apache. Struts. validator. fieldchecks
This is the core verification class used by struts to implement various verification rules. Among them, validatexxx (...) is the name of the method to be created, as long as the rule name is not repeated. Parameters of the validatexxx (...) method:
Object verification is completed on this JavaBean object
Validatemedition the currently executed validatadtion
Field object verified
Actionerrors: If verification fails, an error object of the actionerror object is added.
Httpservletrequest current request object

5. org. Apache. commons. validator. validatorresources
This class is used to replace the string in the MSG Format {n} with ARG

6. org. Apache. commons. validator. validatorplugin
This class is used to initialize validator and save the initialized validatorresources object to servletcontext. The key is validator_key + config. getprefix ().

VII. org. Apache. Struts. validator. Resources
This class is used to initialize A validator object. It first obtains the corresponding validatorresources object from servletcontext through the key value validator_key + config. getprefix. It constructs a validator object with this object as the parameter, and then saves the parameters required by the Verification Method to the parameters attribute of the validator object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.