Use the Validator Framework in Struts (2)

xiaoxiao2021-03-06  109

Resource Binding Resource Binds Used to help messages localization and some other text information. Since it reduces many redundant hardcodes of the application, it is greatly beneficial to the application. For example, if you want to use a "name" tag in the JSP page, you can put this string into a resource binding, then use the resource bound to reference this string instead of direct Using this string, the advantage is that when you want to change this string to "first name", you just need to modify one in the resource binding, without having to modify all the code of the entire application. For the Validator Framework, you can create an error message from the resource binding when the verification rule fails. The Validator framework provides several default messages, which are placed together with the general application message resource. as follows:

#NORMAL RESOURCE BUNDLE MESSAGES

Label.firstname = first name

Label.lastname = Last Name

#Error Messages Used by the Validator

Errors.Required = {0} is required.

.

Errors.maxLength = {0} can not be greater tran {1} character.

Errors.INVALID = {0} is invalid.

...

This verification rule creates an error message when a verification rule fails. The frame will automatically insert the message into the parameter. For example, we use the verification rules of one and the second example. When the checkoutform's firstname property is empty, we will see such an error message: first name is required. You can also modify the binding or profile to show you like Message. "Hang" Validator to Struts Now we have already understood the Validator framework, and it feels good! Below we will quickly tell us how we easily use the Validator framework in the Struts framework. The first thing to do is to let the Struts framework know the Validator framework. You can use Struts1.1's PLUG-IN nature to implement it. Just add the following code in the Struts configuration file:

Property = "pathnames"

Value = "/ Web-inf / validator-rules.xml, / web-inf / value.xml" />

Thus Struts can automatically identify the Validator framework. Another essential step is to create an actionform bean and make sure the Validator framework is available, so it is done. It is not necessary to make some call validation rules or other specific things, the Struts framework automatically completes these work, which is called a statement-based configuration. Then when the verification rule fails, you can use the JSP tag to see the displayed error message. Creating your own Validator Although the Validator Framework has provided you most of the validation rules you need for web applications, sometimes we still need to create some own verification rules. Fortunately, the Validator framework is quite good, providing you with this convenience, and doing this impact on the program is quite small. Creating your own Validator is not a hard thing, just create a Java class that implements this rule. For example, (in foreign countries) should go to the supermarket to buy two pots, to verify that the customer reaches legal drinking age. You can use existing verification rules, but we feel that you have to create a verification rule to verify more straightforward. Verify that the alcohol age rules Validator Java code is as follows: Example 3: Custom Verification Rule Import Java.io.Serializable;

Import javax.servlet.http.httpservletRequest;

Import org.apache.commons.validator.field;

Import org.apache.commons.validator.GenericvaliDator;

Import org.apache.commons.validator.validatorAction;

Import org.apache.commons.validator.validatorutil;

Import org.apache.struts.Action.Actionerro;

Import org.apache.struts.util.strutsValidatorutil;

Public Class NewValidator Implements Serializable {

Public Static Boolean ValidatedRinkingage (Object Bean,

ValidatorAction VA,

Field Field,

ActionerRors Errors, httpservletRequest request) {

String value = NULL;

IF (Isstring (bean) {

Value = (string) bean;

} else {

Value =

ValidatorUtil.getValueAsstring (bean, field.getproperty ());

}

String Smin = Field.getvarvalue ("Drinkingage");

IF (! genericvalidator.isblankornull (value) {

Try {

INT IVALUE = Integer.Parseint (Value);

INT Drinkingage = Integer.Parseint (SMIN);

Ivalue

Errors.Add (Field.getKey (),

StrutsValidatorUtil.getActionError (Request, Va, Field);

Return False;

}

} catch (exception e) {

Errors.Add (Field.getKey (),

StrutsValidatorUtil.getActionError (Request, Va, Field); Return False;

}

}

Return True;

}

Private static boolean isstring (Object O) {

IF (o == null) {

Return (TRUE);

}

Return (String.class.Isinstance (O));

}

}

After you create a new Validator, you just need to add him to the list of existing Validator Frames Validator-Rules.xml, you can use the verification rules you created in your own like using the basic validation rules. Using the Validator Framework in a non-Struts application is talking to us, the Validator framework is originally designed for use in the Struts framework. However, the Validator frame design is quite flexible, and does not directly couple it in the Struts framework so you can use the Validator framework in a normal application to verify. However, you must perform some necessary steps. You can use the configuration file like a web application. This is also another advantage that uses the Validatoe framework. You can locate and load these files in a Struts framework. In a non-Struts application, you must manually locate and load these profiles. Below is a method that the application is generally adjusted at startup:

...

ValidatorResources Resources = New ValidatorResources ();

InputStream Rules =

Validateexample.class.getResourceceAsStream ("Validator-Rules.xml);

ValidatorResourcesInitializer.Initialize (resources, in);

InputStream Forms =

Validateexample.class.getResourceceAsStream ("Validation.xml");

ValidatorResourcesInitializer.Initialize (Resources, Forms);

...

This code snippet created a validatorResources instance and initialized according to two configuration files. Then you can use this ValidatorResources object in your application to verify that you configured JavaBean. Example 4 shows you how to use the initialized ValidatorResources object to verify a Person Bean. Example 4: How to verify your bean using Validator.

/ / Suppose we have created and assembled a CheckoutForm Bean object

Checkoutform form = new checkoutform ();

// Create a Validator using ChekoutForm

Validator Validator = New Validator (Resources, "CheckoutForm");

/ / Tell Validator to verify which bean

Validator.AddResource (Validator.Bean_Key, Form);

// Verify the checkoutform object and store the verification result

ValidatorResults Results = validator.validate ();

In Example 4, we saw that we pass the name of the CheckoutForm Javabean to the Validator class, which is to tell the Validator instance which set of verification rules to verify this bean. As you can see, using the Validator framework in a non-Struts application seems to be a bit non-automated, but it still provides a more flexible solution. Another advantage of using the Validator frame is to isolate the verification from the source code to the external configuration file. This allows us to put more time on our business logic development. The client VS server-side Validator finally explains the Validator framework support for JavaScript. Because some applications need to perform some client authentication, it is necessary to use JavaScript for some client authentication in some time. The client here us generally refers to a web browser. The Validator Framework provides support for rules in the configuration file and automatically generates support for JavaScript verification rules. For each element, it can have one

Child elements and contain some JavaScript code. When the JSP page containing some custom tags is interpreted, JavaScript is also interpreted and these verification rules are performed when the form is submitted. These tags called JavaScriptValidatorTAG are included in the label set of Struts. These tags can be used like this:

The author believes that it is acceptable to use certain JavaScript when needed. When you need to perform some client authentication, use the Validator framework label is also a good choice, and supports localization according to the user's area.

Conclude

So far, I briefly introduced the Validator framework, which is actually some of the surfaces of the frame. The content of this framework is deeply inevitable, and only the regular expression can write a booklet.

Like any framework, the Validator framework provides you a foundation architecture, you can extend and personalize them according to your needs. The most important thing to use the framework of Validator is that they are thousands of hammers and is the essence of technology. You don't need to repeat the mistakes of your failure, you can save more energy to the development of business logic.

About the Author:

Chuck Cavagess: Graduated from Georgia Tech, a computer engineering and scientific degree, has created many Java enterprise systems in the field of medical, banks and b2b, and also the author of O'Reilly's Programming Jakarta Struts and Jakarta Struts Pocket Reference two books.

Author: Chuck Cavaness Translator: javaduke

Programming 小 e eer

转载请注明原文地址:https://www.9cbs.com/read-105420.html

New Post(0)