Use the Validator framework in Struts

xiaoxiao2021-04-05  247

Use the Struts Validator framework author: Chuck Cavaness

Original: http://www.onjava.com/pub/a/onjava/2002/12/11/jakartastruts.html

Translator: javaduke

Email: javaduke@263.net

QQ: 658155

MSN: javaduke@hotmail.com

Each application is responsible for ensuring that the data they are inserted into the latter library is legally effective. After all, if the data relying on these applications is destroyed, it will be disastrous. What can I take anything? Come to make yourself working properly? For example, an application using a regular relational database, each field in the database has its own rules and constraints to ensure that the data stored in it is properly correct. Any application of the Taiwan-funded material database data is responsible for protecting the integrity of the data they submitted.

Any operation attempts to insert or update data that does not meet the standard may be discovered and rejected. This detection may be spread throughout the entire application, and there may be some verification in the performance layer, and the business logic layer, the business logic object is generally verified, and the data is also checked in the post-Taiwan investment.

Unfortunately, since this verification is ubiquitous in the application, it has caused code redundancy of applications to a certain extent. This is not what the app is hoped because this repetitive labor is repeated in a plurality of times, making the application deployment and maintenance take more time. If these validation rules can be reused throughout the app, they will make the application more flexible. In other words, the deployment is faster, the customization is easier, and the program is more flexible.

JAKARTA COMMONS project Validator Framework

Validator is an open source project created by David Winterfeldt, which is also a sub-project for Jakarta Commons. The Commons project is primarily providing some reusable components like Validator. Other well-known Commons components are as BeanUtils, Digester, Logging frameworks, and more. Validator version 1.0 was posted in early November 2002.

Benefits using Validator

Use the Validator framework than the general value of the verification rules in the application's code, such as:

. You can define verification rules for your application;

Verification rules and applications are loose coupling;

The server-side and client verification rules can be defined at the same point;

Configuring a new verification rule or modify an existing verification rule becomes simpler;

Support internationalization;

Support regular expressions;

Can be used for web applications can also be used for standard Java applications;

The method of declaration is realized rather than programming;

In addition to it, Validator's largest feature is its own support of pluggability. After the article

You will see the validation rules built in the Validator framework to better complete your work, and more importantly, the Validator Framework allows you to customize the verification program and insert it into the frame.

Struts and Validator relationships

It should be noted that the Validator framework itself is built due to the Struts framework. Validator's creator David Winterfeldt discovered in the process of using Struts, which requires repeated use of the same verification rule in many ACTIONForm classes, which causes a lot of code redundancy. So he decided to create a Validator framework to eliminate this redundancy, so that Validator was born.

Although the Validator architecture was originally born for the Struts architecture, it was still designed and configured to be used separately from the Struts architecture. This feature allows you to use this frame in any application, don't take it to the Struts architecture. It doesn't affect your application role because you don't use the Struts framework. In fact, this is why Validator is part of the Jakarta Commons project and is not part of the Struts project. Now let's integrate this framework to web applications like the Struts architecture. In the final midth of the article, we will show how to apply it to other types of applications, such as EJB-based applications.

Validator Component Overview

The Validator architecture has the following components:

Validators;

Profile;

Resource binding;

JSP custom label;

Validator Form class;

What is Validators?

A Validator is a Java class that calls the Validator framework when performing a verification rule. The framework calls this Validaotor class based on the method defined in the configuration file. In general, each Validator class provides a separate verification rule, and then these rules can be combined into a more complex rule set.

Note: Sometimes it is convenient, a Validator class can also define multiple authentication rules, and each rule is a static method and does not contain any client status information.

The framework provides 14 default verification rules, sometimes these rules are also known as the "Basic Rules" of the Validator framework, these basic rules, such as Table 1:

Name description

Byte, short, integer, whether the verification can be converted into a corresponding basic data type

Long, Float, Double

CreditCard checks if the input domain is a legal credit card number

DATE Test Your input domain is a legal date

Email check is a legal email address

Mask checks if the input field can successfully match a regular expression

Is the length of the maxlength test value less than or equal to a given maximum length

Is the length of the minlength test value is greater than or equal to a given minimum length

Whether the range of the RANGE test value is between the maximum and minimum values

Required checks if the input field is not empty, or whether the length of the space is not included is greater than zero

Table I

Just as seen in Table 1, the Validator framework provides most of the validation rules that the web application needs. You can use these existing verification rules to create your own verification profile. Despite this, as we mentioned earlier, and later, you can add more Validator according to your needs.

Now let's discuss how to configure these basic validator in a Struts architecture-based application.

The reason for the Validator framework is flexible in that all verification rules and their specific details are implemented by configuring declarations in external files. Your app doesn't have to know these specific verification rules. This feature allows you to expand and modify the rule set, you don't have to move your application's source code. This is very important for you to perform each personalized installation or when the demand changes.

If you use the struts1.1 Validator framework, you will use the two configuration files, a validator- rules.xml, another called validation.xml; actually you can also give them free to name, and you can merge them A XML file. However, you are still best to separate them because they have their own uses. Note: If you download Validator from the Jakarta website, it does not contain both files. These two files can only be found in the Struts of the Validator Framework.

Validator-rules.xml file

Validator-rules.xml file defines the validator that the application can use. Validator-rules.xml acts as a template's role, define the validator that all applications may be used.

Note: This XML file and another XML file we have to discuss below should be placed in the class loader. When we use the Validator framework in a web application, the correct location should be under Web-INF.

Validator-rules.xml file service from validator- rules_1_1.dtd, validator- rules_1_1.dtd can be downloaded in Jakarta.apache.org/struts/dtds/Validator- rules_1_1.dtd. We don't want to spend too much time to study the specific details of this document, we only make some basic introductions here.

The most important element in the Validator-Rules.xml file is included in the element, for example, an example one:

Example: a simple validator-rules.xml file application usage Each validator corresponds to a element. In the example one, I showed two Validator, one is requested Validator and the other is the minimum length Validator. element supports many properties. These attributes are necessary to inform the framework which correct class and method should call this validator. For example, the requested Validator element in Example One indicates that this Validator will call the validateRequest () method of the org.apache.struts.util.StrutsValidator class. Validator may also rely on another Validator, such as the minimum length of the unique length is an example, which contains a Depends property that uses it to indicate that this Validator will depend on request validator. The MSG property specifies a resource binding with a key value, and the framework will use it to generate the correct error message. The use of resource bindings is beneficial to the localization of error messages.

Element also supports child elements, allowing you to specify a JavaScript function running in a client. This allows the server and client verification to be specified at the same point, which makes the application's maintenance simple.

The second profile of the Validation.xml file validator frame is this file called Validation.xml. In fact, you can name it as any name you like, or put it in the validator-rules.xml file.

Validation.xml is used to map all validator you defined in Validator-Rules.xml and components in your application. Since we discussed here is the use of the Validator framework in Struts, then validation.xml here is a mapping of these Validator and Struts. The ActionForm class is actually a class similar to JavaBean, which is used to capture user input and help to transfer these inputs to the next application components in STRUTS. The ActionForm also provides a convenient place to verify these inputs before user input is transmitted to the business logic layer. Example 2 is a simple validation.xml:

Example 2: A simple validation.xml file

Example I show a Name attribute called CheckoutForm's element. CheckoutForm is an Actionform Bean defined in the Struts configuration file. Therefore, the XML file of Example II is to establish this ActionForm Bean and request Validator to set mappings, beans's firstname and lastname properties correspond to the corresponding firstname and lastname elements in the XML file.

In fact, it has many other functions, such as defining constants and global variables in Validation.xml, used to use throughout the file, when you want to make it easier and repeatedly. For more detailed explanations for element and properties of Validation.xml, you can download jakarta.apache.org/struts/dtds/validation_1_1.dtd to see.

Resource binding

Resource binding is 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 messageslabel.firstName = First Namelabel.lastName = Last Name # Error messages used by the Validatorerrors.required = {0} is required.errors.minlength = {0} can not be less than {1} characters.errors. MaxLength = {0} can not be greater Than {1} characterid = {0} is invalid .... When a validation rule fails, this verification rule creates an error message. The frame will automatically insert the message into the parameter. For example, we use the verification rules of one and examples. When the checkoutform's firstname property is empty, we will see such an error message:

First Name is required.

You can also modify bindings or profiles to display messages you like.

"Hanging" Validator to Struts

Now we have learned the Validator framework, 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:

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.

Create your own Validator

Although the Validator Framework has provided you with most of the verification rules that the web application needs, 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 Age Rules of Drinking The Validator Java code is as follows:

Example Three: custom validation rules 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.ActionErrors; 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.GETVARVARUE ("drinkingage"); if (! Genericvalidator.isblankornull (value) {Try {Int iValue = integer.parseint (value); int DRINKINGAGE = Integer.Parseint (SMIN); Ivalue

Use the Validator framework in non-Struts applications

Just as we mentioned earlier, the Validator framework was 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.getResourceAsStream ( "validator-rules.xml"); ValidatorResourcesInitializer.initialize (resources, in); InputStream forms = ValidateExample.class.getResourceAsStream ( "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 equipped with a CheckoutForm Bean Object CheckoutForm form = new CheckoutForm (); // use chekoutForm create a ValidatorValidator validator = new Validator (resources, "checkoutForm"); // tell Validator to verify which Beanvalidator.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.

Client VS server Validator

Finally, we will set up the support of the Validator framework 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 a sub-element and containing 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 Cavage: Graduated from Georgia Tech, a computer engineering and scientific degree, a number of Java enterprise systems in the field of medical, banks and B2B, and both O'Reilly's Programming Jakarta Struts and Jakarta Struts Pocket Reference two books Author.

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

New Post(0)