Struts Principles and Practice (6) Author: Zhang Mei Luo Kuaibo dispatch time: 2004.10.28
This article let us discuss the input verification problem in Struts. We know that the information system has the characteristics of garbage into the trash. In order to avoid the input of junk data, check the input to check the problem in any information system. In traditional programming practice, we tend to check them in places that need to be verified, and most of the things that need to be verified are similar, such as required fields, date, scope, and more. Therefore, it is often full of such a redundant code in the application. It has formed a sharp contrast that struts uses the Validator framework (the Validator Framework is now part of the Jakarta Commons project) to resolve the verification problem, it will check the rule code to concentrate to the outside and to the specific application. XML file In this way, the check logic that appear everywhere is separated from the application, and any Struts application can use this file, and also provides convenience to the extension of the verification rule. It is more difficult to be valuable because the Validator Framework combines some messages to be used in the verification to bind the resource bindings, so that the international programming of the calibration part has become very convenient and natural. The Validator Framework has roughly the following main components: Validators: is a Java class called by the Validator framework, which handles those basic universal values, including Required, Mask (matching regular expressions), minimum length, maximum length, range, Date, etc. XML configuration file: mainly includes two profiles, one is validator-rules.xml, the other is Validation.xml. The content of the former mainly contains some check rules, which contains a collection of some FORMs and their components that need to be verified. Resource Binding: Provides (localized) tags and messages, and the resource binding of Struts is default. That is, some tags and messages used by the check are written in the ApplicationResources.Properity file. JSP TAG: Generate JavaScript Validations for a given Form or Action Path. ValidatorForm: It is a subclass of ActionForm. In order to have a relatively intuitive understanding of the Validator framework, we still demonstrate the use of the Validator framework in front of the login example: First, find a validator-rules.xml file in the mystruts / web-inflicity, below A list of Required authentication partial code involved in this file:
ClassName = "org.apache.struts.validator.fieldchecks" Method = "ValidateRequired" Methodparams = "java.lang.object, Org.apache.commons.valiDator.validatorAction, Org.apache.commons.validator.field, Org.apache.struts.Action.Actionerro, Javax.Servlet.http.httpservletRequest " Msg = "ErrorS.Required"> Var isvalid = true; Var Focusfield = NULL; VAR i = 0; Var fields = new arrival (); orequired = new required (); For (x in orequired) { Var Field = form [orequired [x] [0]]; IF (Field.Type == 'Text' || Field.Type == 'Textarea' || Field.Type == 'file' || Field.Type == 'Select-one' || Field.Type == 'Radio' || Field.Type == 'password') { VAR value = ''; // Get Field's Value IF (Field.Type == "Select-One") { Var si = field.selectedIndIndex; IF (Si> = 0) { Value = Field.Options [Si] .value; } } else { Value = Field.Value; } IF (TRIM (Value) .length == 0) { IF (i == 0) { Focusfield = field; } Fields [i ] = orequired [x] [1]; Isvalid = false; } } } IF (Fields.Length> 0) { Focusfield.focus (); Alert (Fields.Join ('/ n')); } Return isvalid; } // Trim Whitespace from Left and Right Sides of S. Function trim (s) { Return S.Replace (/ ^ / s * /, "") .Replace (// s * $ /, ""); } ]]]] javascript> The code of the validator> 1 section is a verifier that references a server side, and its corresponding code list is as follows: Public Static Boolean ValidateRequired (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 ()); } IF (GenericValidator.isblankornull (Value) { Errors.Add (Field.getKey (), Resources.getActionError (Request, Va, Field); Return False; } else { Return True; } } 2 The section is the error message after verifying the failed. To write the information corresponding to these key values to the ApplicationResources.properity file, the common error information is as follows: # Standard Error Messages for Validator Framework CHECKS Errors.Required = {0} is required. Errors.minLength = {0} CAN NOT BE LES THAN {1} Characters. Errors.maxLength = {0} can not be greater tran {1} character. 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. 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 an invalid credit card number. Errors.email = {0} IS An Invalid E-mail Address. 3 section of the code is used for the JavaScript of the customer, and configures the FORM extremely corresponding field to verify in the validation.xml file. The following is the file. Code: XML Version = "1.0" encoding = "UTF-8"?>
// DTD Commons Validator Rules Configuration 1.0 // En " "http://jakarta.apache.org/commons/dtds/Validator_1_0.dtd"> Depends = "Required, Mask, MINLENGTH, MAXLENGTH">
var>
var>
var> field> Depends = "Required, MINLENGTH, MAXLENGTH">
var>
var> field> form> formset> form-validation> Here you should pay attention to: with The key values in the resource bindings are taken. The error message also said that the error message is also written to the ApplicationResources.properity file, so this provides a good foundation for internationalization. Again, in order to make the server edge verification can be performed, the use of the FORMBEAN from the ActionForm subclass is changed to the subclass of ValidatorForm, namely: Public Class UserInfoform Extends ActionForm to: Public Class UserInfoform Extends Validatorform here, perform server side The verification work has been prepared for almost, at this time, as long as the final step is completed, you can verify the server side. But in most cases, people always want to put these basic simple validations in the customer. In order to verify the customer side, we must also make appropriate modifications to the logon.jsp file. Will Path = "/ logonaction" scope = "session" type = "action.logonaction" validate = "false"> change to PATH = "/ logonaction" scope = "session" type = "action.logonaction" validate = "true"> It is required to perform check 2, place the following code before the tag in the struts-config.xml file. Its function is to combine each component for verification. Value = "/ Web-inf / validator-rules.xml, / web-inf / value.xml" /> plug-in> To this, our work is ready, you can enjoy your own labor results, try to enter a variety of combined user names and passwords to see their verification results. Careful experience you will find that the verification of the server is more comprehensive, such as the verification of the character length of Password. Reference: "Struts in action" TED husted Cedric Dumoulin George Franciscus David Winterfeldt, "Programming Jakarta Struts" Chuck Cavaace