Struts validator Check Form

Source: Internet
Author: User
Tags to domain

Use the rich built-in verification methods provided by validator to simplify struts development.
A major benefit of the Struts framework is that it provides a built-in interface for verifying received form data. If any verification fails, the application will re-display the HTML form to correct invalid data. If the verification is successful, the process continues. The simple validation interface of the Struts framework reduces the headaches related to data verification, so that you can focus on the verification code, instead of using the techniques of capturing data and re-displaying incomplete or invalid data.
However, the Built-in validation interface of Struts also has disadvantages. For example, verification code is often repeated across an application because many domains need the same verification logic. Any modification to the verification logic of some similar fields requires that the code be modified in several places and the affected code be re-compiled. To solve this problem and enhance the struts verification interface function, the validator framework is created as a third-party attachment of struts. Later, validator was integrated into the core struts code library and separated from struts. Now it is an independent Jakarta Commons project. Although validator is an independent framework, it can still be provided after being encapsulated with other programs and seamlessly integrated with struts.
Validator Overview
Without validator, you have to write all the code required to verify the form data and put it in the validate () method of the form bean object. For every form bean field on which you want to perform data verification, you need to write logic code for verification. In addition, you must write code to store error messages when verification fails.
With validator, you do not have to write any code in form bean to verify or store error messages. On the contrary, form bean provides an actionform subclass of validator, which provides the ability to verify or store error messages.
The validator framework can be installed as a system of pluggable verification routines that can be used for form bean verification. Each verification routine is only a Java method responsible for executing a specific type of verification tasks. The verification may pass or fail. By default, validator is provided together with several useful verification routines that meet verification requirements in most cases. However, if the validator framework does not provide the verification routine you need, you can create a custom verification routine and insert it into the framework. In addition, validator also supports server-side and client-side (JavaScript) verification, while form bean only provides the server-side verification interface.
Validator uses two xml configuration files to determine which verification routines to install and how to apply them to a given application, respectively. The first profile validator-rules.xml description should be inserted into the validation routine in the framework and provide the name of each validation logic. The validator-rules.xml file also defines the client JavaScript code for each validation routine. You can configure validator to send the JavaScript code to the browser, so that the verification can be performed on the client and server.
The Second Configuration File validation. xml determines which form bean the validation routine applies. The definitions in the file use the logical name of the form bean given by the struts-config.xml file and the logical name of the validation routine given by the validator-rules.xml file to associate the two.
The validator framework is used to enable the validator plug-in, configure two configuration files for validator, and create form beans that provide the actionform subclass of validator. The following describes how to configure and use validator.
Enable validator plug-in
Although the validator framework is provided together with Struts, validator is not enabled by default. To enable validator, add the following plug-in definitions to the struts-config.xml file of your application.
<! -- Validator configuration -->
<Plug-in classname = "org. Apache. Struts
. Validator. validatorplugin ">
<Set-Property = "pathnames"
Value = "/WEB-INF/
Validator-rules.xml/WEB-INF/
Validation. xml "/>
</Plug-in>

 
This definition tells struts to load and initialize the validator plug-in for your application. During initialization, the plug-in loads a list of validator configuration files specified by the path name attribute separated by commas. The path of each configuration file should be specified by the path related to the web application, as shown in the previous example.
Please note that the struts-config.xml file for your application must be consistent with the struts configuration document type definition (struts configuration document type definition, DTD), which specifies the order in which elements appear in the file. Therefore, you must place the validator plug-in definition in the appropriate location of the file. The easiest way to ensure proper arrangement of elements in a file is to use tools such as the struts console, which automatically formats your configuration file to be consistent with the DTD.
Configure validator-rules.xml
The validator framework can be set to a pluggable system. Its Verification routine is just a Java method that is inserted into the system for specific verification. The validator-rules.xml file is implicitly inserted into the verification routine that validator is used to perform verification. The struts example application carries the pre-configuration copy of this file. In most cases, you do not have to modify this pre-configuration copy unless you want to add custom verification to the framework.
Listing 1 is a sample validator-rules.xml file that describes how to insert a validation routine into validator. Each validation routine in the validator-rules.xml file has its own definition, which is declared with validator marking, using the name attribute to specify the logical name for the validation routine, and specify the classes and methods of the routine. The logic name of the routine is used to reference other routines in the file and the validation definitions in the validation. xml file.
Note that the validator tag is placed in the Javascript tag, which defines the client JavaScript code to perform the same verification on the client and on the server.
Provided Verification Procedures
By default, validator includes several basic verification routines that you can use to handle most verification issues. These routines have logical names, such as required (for entering the required value), creditcard (for entering the credit card number value), email (for entering the email address value), and so on.
Create form Bean
To use validator, the form bean of your application must be a subclass of validator's actionform, rather than the actionform itself. The actionform subclass of validator provides the implementation process of the validate () method of actionform (which is embedded in the validator framework. You don't have to write the verification code from the beginning and put it into the validate () method. On the contrary, you can ignore this method completely because validator provides you with the verification code.
Similar to the core functions provided by struts, validator provides you with two optional methods to create form beans. The first method you can choose is to create a specific form bean object as follows:
Package com. jamesholmes. minihr;
Import org. Apache. Struts. validator
. Validatorform;
Public class logonform extends validatorform {
Private string username;
Private string password;
Public String GetUserName (){
Return username;
}
Public void setusername (string
Username ){
This. Username = username;
}
Public String GetPassword (){
Return password;
}
Public void setpassword (string
Password ){
This. Password = password;
}
}

 
This class is similar to the class you created using validator, but it provides validatorform instead of actionform. This class also does not provide the implementation process of the empty reset () and validate () Methods of actionform, because validatorform provides the corresponding process.
The method for configuring this specific form bean in the struts-config.xml file is the same as the method for configuring the regular form Bean:
<Form-beans>
<Form-bean name = "logonform"
Type = "com. jamesholmes
. Minihr. logonform "/>
</Form-beans>

 
The logic name specified for a specific form bean by using the name attribute marked by the form is the name used when the validation is defined in the validation. xml file, as shown below:
<! Doctype form-validation
Public "-// Apache Software Foundation //
DTD commons validator rules
Configuration 1.0 // en"
"Http://jakarta.apache.org/
Commons/dtds/validator_00000.dtd ">
<Form-validation>
<FormSet>
<Form name = "logonform">
<Field property = "username"
Depends = "required">
<Arg0 key = "prompt. username"/>
</Field>
</Form>
</FormSet>
</Form-validation>

 
Validator uses the value of the name attribute marked by the form to match the validation definition with the name of the form bean to which these definitions are applied.
The second option you can choose when creating form beans is to define a dynamic form bean in the struts-config.xml file, as shown below:
<Form-beans>
<Form-bean name = "logonform"
Type = "org. Apache
. Struts. validator. dynavalidatorform ">
<Form-property name = "username"
Type = "Java. Lang. String"/>
<Form-property name = "password"
Type = "Java. Lang. String"/>
</Form-bean>
</Form-beans>

 
Dynamic form bean does not require the creation of specific form bean objects. Instead, you need to define the attributes and types that form bean should have, while struts dynamically creates form bean for you. Validator allows you to use this concept, just like using it in core struts. The only difference from validator is that you must specify that form bean is of the org. Apache. Struts. validator. dynavalidatorform type, rather than the org. Apache. Struts. Action. dynaactionform type.
The logical name assigned to the dynamic form bean is the name used to define the validation in the validation. xml file. Validator uses a matched name to associate these verifications with form bean.
In addition to the two standard methods for creating form beans, validator also provides an advanced feature to associate Multiple Validation definitions with one form bean definition. When you use form beans based on validatorform or dynavalidatorform, validator maps form beans to validation definitions in the validation. xml file using the logical name of form beans in the struts-config.xml file. This mechanism is useful in most cases, but in some cases, form Bean must be shared among multiple operations. One operation may use all fields of form Bean (fields), while the other operation may only use one subset of these fields. Because the verification definition is connected to form bean, operations that use only one subset of the domain cannot bypass the verification of unused domains. When form bean is verified, an error message is generated for unused domains, because validator does not know to verify unused domains. It simply regards them as missing or invalid.
To solve this problem, validator provides two additional actionform subclasses that enable you to associate verification with operations rather than form bean. In this way, you can specify which authentication is used for the form bean based on which operation is being used. For a specific form bean, declare the org. Apache. Struts. validator. validatexceptionform subclass as follows:
Public class addressform extends validatemeditionform {
...
}

 
For dynamic form beans, specify the org. Apache. Struts. validator. dynavalidatexceptionform type for form bean definitions in the struts-config.xml file, as shown below:
<Form-bean name = "addressform"
Type = "org. Apache. Struts
. Validator. dynavalidatexceptionform ">
...
</Form-bean>

 
In validation. in the XML file, a set of verifications are mapped to an operation path instead of form bean name, if you define the create address and edit address operations (they use the same form bean), each operation has a unique operation name, as shown below:
<Action-mappings>
<Action Path = "/createaddress"
Type = "com. jamesholmes
. Minihr. createaddressaction"
Name = "addressform"/>
<Action Path = "/editaddress"
Type = "com. jamesholmes
. Minihr. editaddressaction"
Name = "addressform"/>
</Action-mappings>

 
The following validation. xml file snippets show two groups of verifications, which are used for the same form bean but have different operation paths:
<FormSet>
<Form name = "/createaddress">
<Field property = "city"
Depends = "required">
<Arg0 key = "prompt. City"/>
</Field>
</Form>
<Form name = "/editaddress">
<Field property = "state"
Depends = "required">
<Arg0 key = "prompt. State"/>
</Field>
</Form>
</FormSet>

 
Because form bean either belongs to the validatexceptionform subclass or the dynavalidatexceptionform subclass, validator knows to use an operation path instead of the form bean logical name to find the form bean for verification.
Configure the validation. xml file
The validation. xml file is used to declare a set of verifications that will be applied to form beans. Each form bean to be verified has its own definition in this file. In this definition, specify the verification of the fields to be applied to the form bean. The following is an example of the validation. xml file, which describes how to define verification:
<! Doctype form-validation
Public "-// Apache Software Foundation //
DTD commons validator rules
Configuration 1.0 // en"
"Http://jakarta.apache.org/
Commons/dtds/validator_00000.dtd ">
<Form-validation>
<FormSet>
<Form name = "logonform">
<Field property = "username"
Depends = "required">
<Arg0 key = "prompt. username"/>
</Field>
<Field property = "password"
Depends = "required">
<Arg0 key = "prompt. Password"/>
</Field>
</Form>
</FormSet>
</Form-validation>

 
The first element of the validation. xml file is form-validation. This element is the main element of the file and is defined only once. Define the form-set element in the form-Validation Element, which includes multiple form elements. Generally, only one form-set element is defined in the file, but to internationalize the verification, a form-set element should be used separately in each place.
Each form Element uses the name attribute to associate the name with the field verification set it contains. Validator uses this logical name to map these verifications to a form bean defined in the struts-config.xml file. Based on the form bean type to be verified, validator strives to match the name with the form bean logical name or operation path. In a form element, the field element defines the verification of the specific fields to be applied to form bean. The property attribute of the field element corresponds to the domain name in the specific form bean. The depends property uses the validator-rules.xml file to specify the logical name of the validation routine, which will be applied to domain verification.
Configure applicationresources. Properties
Validator uses STRUTS's resource bundle mechanism to embody error messages. The error message does not need to be hardcoded in the framework. validator enables you to specify a key value for a message in the applicationresources. properties file. If verification fails, this key value is returned. Each validation routine in the validator-rules.xml file uses the MSG Property marked by validator to specify the key value for the error message, as shown below:
<Validator name = "required"
Classname = "org. Apache
. Struts. validator. fieldchecks"
Method = "validaterequired"
Methodparams = "Java. Lang
. Object, org. Apache. commons. validator
. Validatemedition, org. Apache. commons
. Validator. Field, org. Apache. Struts
. Action. actionerrors, javax. servlet
. Http. httpservletrequest"
MSG = "errors. Required">

 
If the verification fails when the verification routine is running, the message corresponding to the key value specified by the MSG attribute is returned.
The following snippet shows the default message set for verification errors from the applicationresources. properties file, which are provided by the struts sample application. The keys for each message correspond to each message specified by the validation routine in the validator-rules.xml file, which is provided by the struts sample application.
# Error messages for validator framework Validations
Errors. Required = {0} is required.
Errors. minlength = {0} cannot be less than {1} characters.
Errors. maxlength = {0} cannot be greater than {2} characters.
Errors. Invalid = {0} is invalid.
Errors. byte = {0} must be a byte.
Errors. Short = {0} must be a short.
Errors. Integer = {0} must be an integer.
Errors. Long = {0} must be a long.0. errors. Float = {0} must be a float.
Errors. Double = {0} must be a double.
Errors. Date = {0} is not a date.
Errors. range = {0} is not in the range {1} through {2 }.
Errors. creditcard = {0} is not a valid credit card number.
Errors. Email = {0} is an invalid e-mail address.

 
Note that each message has a placeholder in the form of {0}, {1}, or {2 }. During running, the placeholder is replaced by another value, such as the name of the verified domain. This feature is particularly useful, allowing you to create common verification error messages that can be reused by several different domains.
For example, the following error message errors. Required for required verification is provided:
Errors. Required = {0} is required.

 
When you use the required verification in the validation. xml file, you must define the value used to replace {0} in the error message, as shown below:
<Form name = "auctionform">
<Field property = "Bid" depends = "required">
<Arg0 key = "prompt. Bid"/>
</Field>
</Form>

 
An error message can contain up to four placeholders: {0} and {3 }. These Placeholders are called arg0 to arg3 respectively. You can use arg0 ~ Arg3 flag to specify them. In the preceding example, the arg0 flag specifies the value used to replace the {0} placeholder. The key attribute of this tag specifies a Message key value from the applicationresources. properties file. Its value is used to replace the placeholder, as shown below:
Prompt. Bid = Auction Bid

Replace the placeholder value with the Message key value, which eliminates the need to recode the replacement value in the validation. xml file. However, if you do not want to use the resource bundle's key value/value mechanism to specify the placeholder value, you can use the following syntax of arg0 to explicitly specify the placeholder value:
<Arg0 key = "Auction Bid" resource = "false"/>

 
In this example, the value of the resource attribute is set to false to notify validator to use the value specified by the key attribute as the placeholder value instead of applicationresources. A key value of the message in the properties file.
Enable client Verification
Validator not only provides a framework to simplify the form data verification process on the server side, but also provides an easy-to-use method for performing client verification. Every verification routine defined in the validator-rules.xml file can specify JavaScript code at will, which can be run in a browser (on the client, in this way, the verification process is the same as that of the server. When the client performs verification, these forms are not allowed to be submitted unless all forms are verified.
To enable client verification, you must add the Javascript tag of the struts HTML Tag library (TAG Library) to each JSP to be verified, as shown below:
<HTML: javascript formname = "logonform"/>

 
Javascript markup requires that the formname attribute be used to specify the form definition name given in the validation. xml file for the form to be verified, as shown below:
<Form name = "logonform">
<Field property = "username"
Depends = "required">
<Arg0 key = "prompt. username"/>
</Field>
<Field property = "password"
Depends = "required">
<Arg0 key = "prompt. Password"/>
</Field>
</Form>

 
All the verifications for the specified server for the form definition will be run on the client. Because client-side verification is executed in Javascript, there are multiple ways not to execute it. Make sure that the verification process is always running, whether or not you choose to enable client verification, validator performs these verification on the server.
Conclusion
The validator framework provides a configurable System for form data verification, thus adding many valuable functions to the core Struts framework. By applying the validator framework to your applications, you can save time and simplify the development process of struts applications.

 

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.