"Struts in action" Chapter 12 Translation, First Draft, Section 1

zhaozj2021-02-16  73

Struts in Action Chapter 12, LAMP5W Translation (Lamp5w@yahoo.com.cn)

Validating user input (check user input)

Understand the needs of "data check"

Configure and use Commons Validator

Use multiple pages and localized verification

Write your own Validator

US: Programming Work has become a software engineer strive to build a larger and better fool program and the universe trying to make a competition between more more idiots. At present, the universe is a winner. --Rich Cook

I never know how much it is true. --Bette Midler

12.1

Most web applications need to collect data from the user. Enter the text domain or GUI element such as a menu list, a radio button, multiplex box, and so on. Practice shows that what users entered are not always rational. Some menu options may be mutually exclusive. A phone number may miss a number, the alphabet may be input to the digital field, and the same number may also be input to the field that I want the user to enter letters. This may be because the form of registration data is not smart enough or because the user is not paying attention, but things happen in any case - and the possibility is very large.

Nothing is more frustrated than users from the application's feedback, even because the user first puts the garbage to the app. A rigorous application should prevented all the mistakes that can be predicted in advance, and also protect the user itself. After all, if the user makes a mess, the result is still to help him correct. 12.1.1 Please allow me to reject your input in a traditional app, the data entry control can easily put the poor data on the door, but it is a luxury "modal". ------------------------------------------------definition: A user interface element, when it requires all users to enter an application input "mode". Other elements cannot be accessed before this element is not released. To make the program continue to run, the user either fills the entire modal dialog box or therefore only shuts down the application. Most user interface elements are "non-modal". ---------------------------------------------- WEB application Program, natural is "non-modular", only a small number of options. By default, the HTML element displayed by the browser accepts any input, and a given element does not know anything outside of the form. We can make a joke with JavaScript, but we can't guarantee that users will allow JavaScript in the browser. Of course, we can check it when data arrives at the business logic layer. (More on the application "layer" and business objects, see Chapter 2 of this book.) Many business logic objects have built-in data check capabilities, but most business objects are The data will not be reviewed before receiving data. The business layer method is more trusted guy, and they expect friendly objects to provide reasonable data and work as they claimed, even when business objects are in the most conservative situation, usually everything they can do is Throw an exception. Enter a sick dialogue and users to change his input should not be the responsibility of the business object. Of course, verify data in the context environment is the responsibility of the business object, for example, if a username and password meet the conditions. However, before the data exchanges to the business layer, there is a lot of target verification rules to be implemented. In a distributed application, a business object may reside on a remote machine, creating a connection to and from a client and a server to solve a simple data input error will be very expensive. 12.1.2 Web Layer Check In practice, you often enter the web application framework to provide target verification tasks and reduce the gap between Model and View. In non-mode, in distributed environments, we need to verify the task to do the following:

Make sure the determined field value determines a given value to immediately check the entire Form data in the desired mode and range and return a message list to display localized messages when the value correction behavior between fields To return to the original input. In the case where JavaScript is disabled, the other two important features of the server check verification system is that low coupling and optional client verification low coupling as an actual problem, the input needs to be verified by the controller, but business validity The calibration is tied to the business layer. This means that the verification rules should be stored between the page tags and Java code to allow them to be reviewed and modified without changing any other source code. Keeping calibration rules The low coupling can easily implement synchronization between it and business needs. ------------------------------------------------definition: The degree of coupling involves the association intensity between the two components. Coupling is a supplement to the consolidation. Corporation describes the relationship between the intrinsic content of a component, the purpose is to create components with intrinsic integrity (strong polymerization), smaller, direct, visible, and other components to maintain flexible relationships (low) coupling). [Mcconnell] ----------------------------------------------- - Some verification rules may also require localization. When adding support to a new region, we should be able to update the verification rules, such as the easy update resource binding. When the verification rule may be convenient to the representation layer, it is important to remember that they are actually belonging to the business layer. The verification logic should not be mixed with the code of the layer. The client verifying that the customer is unreliable. Kid a web page submission and bypass the script of any original page is a very easy task. When we cannot rely on client JavaScript check, they are still useful, it can feedback immediately to avoid excessive interaction with the server, saving any time and bandwidth of anyone. So, another ideal feature produces JavaScript and server checks from the same verification rules. When JavaScript is enabled, the input can be verified by the client before committing, if JavaScript is not enabled, then the input will be verified by the server to ensure that no error is not. 12.1.3 Validator Consequences Use Jakarta Commons Validator [ASF, Validator] to find the following inference:

Validator is a framework component that can achieve these requirements - and even more Validator configured by an XML file, which generates the rules defined by the fields in the form. Validator defined by the XML file is also configured as a basic type (for example, Dates, Integers) Prepared Validator is ready-made, if needed, you can create your own verifier regular expression can be used by mode-based check, such as postal coding and telephone numbers to support multi-page and localized verification, you can be any Language Writing Wizard --------------------------------------------- - Definition: Regular expression is based on some modes to match the formula of the string. Regular expressions are applied to many UNIX command lines and programming tools. For more information on regular expressions, please refer to Stephen Ramsay's "Using Regular Expressions" webpage. ------------------------------------------------over you Using Jakarta Commons Validator to bring many benefits: Optimization of resources: When JavaScript is enabled, it can be provided, and the calibration of the server is also guaranteed. Single maintenance: The verification of the client and the server is guaranteed by the same configuration. Scalability: Customer verification can define maintainability through regular expressions or Java code: it is a low coupling relationship between it and the application, does not need to change the page tag or code localization when maintenance: localized verification only Defined with Struts integration when needed: By default, the check will share the message binding of Struts. Localized texts can be concentrated and to easily deploy client verification: To use client checks, you only need to add a separate JSP tag to generate check scripts and submit forms through the script. Easy configuration: Validator is configured using an XML file, just like the deployment description of the web application and the configuration of Struts, but of course, they still have a shortcoming:

Non-mode client verification: The javascript generated by the verifier is non-mode; it does not interfere with the user's input behavior until the form is submitted

Dependency: The check is separated between the fields and the ACTIONFORM attribute. Page tags, actionform, validator, and struts configuration files must be synchronized together

Lack of data conversion and conversion: Validator package does not provide data conversion and conversion function, when needed, data transformation and transformation must be implemented individually.

Keep in mind that using Jakarta Commons Validator in your application is not a spirit of the drug, some calibration can only be implemented by the server. If the server verification fails, the displayed error message is different from the JavaScript message. The intervention of the interface will make the user confused. ------------------------------------------------definition: Data Conversion is to convert data from one type to another, for example from String to Integer. Data Transformation is the intrinsic format that changes the data, for example, to append a punctuation in a string display or to remove unwanted punctuation before it stores. Localization can require conversion data into a display format. ------------------------------------------------ in this chapter In this, we will show how best to use the Commons Validator framework in your application, including the full design of Validator and introduce a simple example. We will focus on every component of Validator, along with frequently needed (original: offen-needed) technology, such as the most important default message, cancel the check, use multi-page workflow, check collection, etc. It is important to emphasize that purpose is important. The data entry check is not a mixed solution (original: Omnibus solution), without accessing MODEL, many types of errors cannot be discovered. We can check if a username and password meet the needs of the business in length and ingredients, but if you want to know if the combination of a username and password is correct, we need to go to the business layer to verify the data service. However, in our request (business layer), the review data is possible correctly, we can save expensive data access transactions, which is good for anyone. ------------------------------------- Note: You may worry, "Then I should use struts. Is the frame or Struts Validator framework to build my app? "At the same time, in fact. Many applications are built using multiple framework components, including some development teams developed at home. Struts is built on the Sun's Java J2SE frame frame framework, the Struts Validator is based on the Struts framework, so you can use many classes like many packages in many packages. . For more information on using the framework system, please refer to Chapter 2 of this book. ------------------------------------ Chapter 4 contains how to set the Validator with Struts1.1 Content, this chapter is how developers will practice Validator practices the wizard in your application. 12.2 Struts Validator overview ---------------------------------- Let us see how struts validator is The components are interacting to provide client and server verification services through the same verification rule settings. You may be surprised that once the validator combines all the items to check how easy your data is.

Table 12.1 lists many sectors that make up the Struts Validator. Table 12.1 Main Struts Validator Components

Component Description Validators (Verifier) ​​Handling native and other common types. Basic Verifiers include "required" (Mask "(matching regular expression), minimum length, maximum length, range, native type, date, email, and credit card number. Custom (or plug-in) Verifier can also be defined. Resource Bundle provides (localized) tags and messages. Share Struts messages by default. XML Configuration File defines a form and verifier for a field that requires a verified field, which can be defined in separate files. JSP TAG (JSP Tag) Generates a JavaScript Verifier for a given form name or Action path. ValidatorFrom automatically checks properties based on the Form bean name (runtime through the validate method specified by the actionmapping parameter). You must be extended to provide a list of attributes of the form ValidatorActionForm automatically check the properties based on the Action path (running by the validate method specified by the actionmapping parameter). It must be expanded to provide the properties expected by the form, Commons Validator is created as an extension of the Struts framework, but since it can be used in the framework, developers contribute it to another Jakarta items - Commons. The Struts release contains a validator package that contains many classes integrated with Commons Validator and Struts. This package is expanded with the Commons Validator package to develop Struts Validator. In this chapter, in this chapter, we mention that Struts Validator is a supercoming of Commons Validator. The Validator package is actually a collection of validator objects written by Java. Each Validator object performs a rule for the properties of another object, in Struts Validator, these objects are ActionForm. The verifier has a standard entry method, like the Struts action, is used to call the checker when needed. The Validator profile allows you to associate one or more checkers for each property in your form. In practice, many applications need to perform a number of checked verifiers. Some fields may require input data, and a postal coding abbreviation may always know the length, and other universal field types include numbers, date, and credit card numbers. Among them, Validator is equipped with many basic validers to handle these general needs. If a basic verifier or a regular expression cannot meet your Validator, you can get into your own validator and insert it into the package. Basic Verifiers only bundled their own plugins, your custom checkor can do any basic verifier can do, or more. Your application needs to be used, basic, or custom, can be specified inside an XML configuration file, usually named Validation.xml. For maintenance work, you can include the rules that associate a Validator to your ActionForm property into a specified file, usually named Validator-Rules.xml. ------------------------------------- 1.0 VS 1.1 in the Validator version of Struts 1.0, use A single validation.xml file contains a Validator definition and a formatter.

Struts1.1 allows you to separate these components to separate files. In this chapter, we will mention the use of Struts1.1 independent files. If you are using struts1.0, all configuration elements remain in a single validation.xml file. ------------------------------------- Check Rules files have a

element usually and you The element of the Struts application. elements are in the sub-elements. Each element can specify that it must be successful through the checks of one or more verifiers. If a check device fails, it can feedback a message template that follows any keywords replacing the parameters, Struts uses that keyword and parameters to generate a localized error message. If the client verification can be used, the same message can be displayed in the JavaScript window, as shown in Figure 12.1. The check file is where you insert the basic verifier you need to check the verification rule or where you can specify which Validation class you can use, follow the optional client JavaScript. When using, the JavaScript check must pass before the form is submitted to the application. Next to the JavaScript element of the verifier profile, another client's check is tag (struts1.0) or tag (Struts1.1). If you place this tag anywhere in the JSP page, it will be invoked by a single script to a separate script in a separate script, then you can use the tag onSubmit Attributes call all inlet methods. If the JavaScript check, the form will be submitted, otherwise a pop-up window will output a localized error message. To enable server validation, you can simply extend your ActionForms from the base class in a validator package. ValidatorForm (Org.apache.struts.validator.validatorform) Class corresponds to standard ActionForm. The ValidatorDynform class (org.apache.struts.validator.dyNavalidatorForm) corresponds to DynaActionform. By default, the Validator element matches the ActionForm using the attribute or the FormBean name. Both selection one, you can use ValidatorForm (org.apache.struts.validator.validatorform) or ValidatorDynform (org.apache.struts.validator.Dynavalidatorform) to match elements, this match uses the ActionMApping path to implement. Figure 12.1 In the JavaScript message window generated by Struts Validator, we will use a login application as the background of the client and the server to show you how to put all these things together.

-------------------------------------- 2.0 VS 1.1 in the release version of 1.1, Struts Validator is bundled in the Struts JAR file and is arranged as an optional component of the formal release. Important and some secondary achievements have changed, but the package is inherently no change. Different, we will show a separate list for each release version. --------------------------------------- 12.2.2 Login example cooperation with Chapter 3 The Struts Validator login program will help us clarify how these components are harmonious together. Then, in Section 12.3, we will in-depth deployment of each component. After you set up the relevant bag (see Chapter 4), your next step is to determine the verboress you need in your hand. These validers can be saved in a separate file, the default named Validator-Rules.xml. Our example only uses the Required checkor, although most applications also use many other checkers. In the next content, we will see our needs and use struts validator to check a pair of usernames and passwords. The Validator-Rules.xmlstruts Validator Distribution Edition contains the verbox and other common requirements of the native type, like e-mail and credit card verification. In practice, in general, those basic verbs can already meet all your needs, if not, you can write your own verifier and define them together in the Validator-Rules.xml file and the basic verifier (Be noted is that in Struts 1.0, the verifier and form checks are defined in a single validation.xml file). Listing 12.1 and 12.2 will list the Java and XML source code for the Required Checkler under Struts1.1, more about writing your own plug-in verifier, see Section 12.9.

Listing 12.1 Required Checkler's XML source code (struts1.0) classname = "org.apache.struts.util.strutsvalidator" method = "validaterequired" MethodParams = "java.lang.object, org.apache.commons.validator.validatorAction, org.apache.commons.validator.field, org.apache.struts.Action.ActionerroS, Javax.Servlet.http. HttpservletRequest "MSG =" ErrorS.Required "> ------------------------------------ 1 This section contains reference to the server Validator ( See Listing 12.2). 2MethodParams only used in Struts1.1 3 client JavaScript is included in the XML element like we can see, the validator element is defined in two parts:

The Java class and method for the server-ended Java class and method are displayed in Listing 12.2. Listing 12.2 validateRequired method Java code (Struts1.1) 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 (), StrutsValidatorUtil.getActionError (request, va, Else false;} else {return true;}} ----------------------------------- - Application.properties If a verifier fails, it returns a message keyword and alternative parameters that can be used with standard resource bundles. By default, Struts Validator share resource bindings that are used by the rest of your application, usually named ApplicationResources.properties, or simply application.properties. When another message is not specified, the Struts Validator will automatically find messages in the default resource binding. Usually create a keyword for messages, use "." (Dot) and verifier name to connect Errors, Required Checkler entry looks below: ErrorS.Required = {0} is required. When we configure a field that uses the Required Verifier, we also use the label of the fields that can be replaced. The verifier can then reuse the same messages for all Required fields. Option 1, you can define your own message to selectively override default messages (see Section 12.4.3). Resource Binding will contain other messages you need for your application, along with the tags specified by Struts Validator, and messages you need.

Here is something you need for our "UserName" and "Login" check: # - logon --logon.username.maskmsg = username must be letters and numbers, no spaces.logon.password.maskmsg = Password Must Be We also need labels for the "UserName" and "Password" fields, however, if the application has been localized, they have been provided: logon.usename.displayName = Usernamelogon.password.displayName = Password Note, we use "Logon" as a prefix for labels and messages, give each form, you can avoid the conflicts of application growth (extensions). Validator.xml When you define our "FormSet" element in the validator.xml file, the verifier and message key are used, such as Listing 12.3.

Listing 12.3 A Formset element mask ^ [A-ZA-Z0-9] * $ < VAR-Name> minlength 5 ------------------------------------ 1 a "formet" is One or more form packages. 2 Each FORM element is given a self-owned name (name), which will comply with the FORMBEAN name or Action path in your Struts Configuration. 3 Each Form element consists of many Field elements. The 4field element and the Depends property specifies the specific MSG element to use to use the optional MSG element that allows you to specify a custom message keyword for a checker and a message key 6Arg0 element that can be used for any alternative parameters. Specify the first alternative parameters, any messages that need them can use to deliver variable attributes to the Checkler 8 Here we pass a regular expression to the "Mask" verifier, Expressions, usernames Only characters and numbers in the alphabet can be included. 9 Here we say that a password is a must and the length must be greater than 5 characters. The password length is a business requirement, allowing the account more secure.

Password check messages use the default "minLength" or "Required" message, these messages are defined in the validation-rules.xml file (ErrorS.minitionth and ErrorS.Required). JSP tag /logon.jsp JavaSctipt check is optional, but you can easily implement if you want to use them in your application. Listing 12.4 shows the logon.jsp that is improved to display the JavaScript check.

Listing 12.4 Logon.jsp Prepare <% @ Taglib Uri = "/ Tags / Struts-HTML" Prefix = "HTML"%> <% @ Taglib URI = "/ Tags / Struts-Validator "prefix =" Validator "%> sign in, please! </ title> </ head> <body> <! - 2 -> <html: form action = "/ logonsubmit" FOCUS = "username" οnsubmit = "Validatelogonform (this)"> <table border = "0" width = "100%> <TR> <TH align =" right "> username: </ tH> < TD align = "left"> <html: text property = "username" /> </ td> </ tr> <tr> <tr> "right"> password: </ th> <td align = "left" > <Html: Password Property = "Password" /> <TD> </ tr> <tr> <TD align = "right"> <html: submit property = "submit" value = "submit" /> </ td > <Td align = "left"> <html: reset /> </ td> </ tr> </ table </ html: form> <! - 3 -> <validator: javascript formname = "logonform" / > </ Body> </ html> --------------------------------------- - 1 Here we import the label library 2 of the Verifier 2 This section calls the verifier script, then, the form is submitted 3 Here we add a tag to output the JavaScript check method in any location of the page (</p> <p>Validate method) To enable server verification, all to do everything is just letting FormBean inherited ValidatorForm instead inherited an actionform public class logonform extends org.Apache.Struts.validator.AlidatorForm {} and removing the original validate method. When the controller calls the validate method, the ValidatorForm method will kick the Validate method and follow the rules defined in the validation.xml file. 12.3 Basic Checkers ----------------------------------- As shown in Table 12.2, Struts Validator A 14 basic verifier comes with. These verifiers basically cover the needs of most applications, if there is any other need to be generated, like we can add a custom or plugin in the form of the verifier. Table 12.2 Basic Verifier</p> <p>Verifier Uses Required Success Condition: Field contains any character MASK success conditions except blank: The values ​​given the regular expression of the Mask property: Specified values ​​in the MIN and MAX properties Within the range ((value> = min) & (value <= max)) MaxLength Success: Field length is less than or equal to Max property MINLENGTH Success condition: Field length is greater than or equal to max attribute Byte, Short, Integer, long , Float, Double Successful Condition: The values ​​of the validation can be converted to the corresponding native type Date Success condition: The validated value is described in the valid date, which may need to provide the date-based ReditCard Successful condition: Valued values Is a valid credit card number Email Successful condition: The validated value is a valid email address 12.3.1 Required Checkler Required Checker is the simplest and most common verifier: <Field Property = "Customerid" Depends = "Required" /> If there is no thing or only blank input into a field, this verifier will fail, and an error is passed back to Framework, otherwise, the verifier is successful. To determine if a field contains only a blank, the standard string.trim () method is called (value.trim (). Length () == 0). Because the browser does not submit an empty field, any non-Required field will skip all check devices if the field is empty or length is zero. 12.3.2 Mask Checker Mask Checker Check and Regular Expression The opposite value, if the pattern matches, the verifier is successful. <Field Property = "Postalcode" depends = "mask"> <arg0 key = "registrationform.postalcode.displayName" /> <var> <var-name> mask </ var-name> <var-value> ^ / d { 5} / d * $ </ var-value> </ var> </ field> Jakarta regexp package is used to resolve regular expressions. If an expression needs to be used more than one field, it can also be defined in the validation.xml file as a constant (constant), for example: <constant> <constant-name> zip </ constant-name> <constant-value > ^ / d {5} / d * $ </ constant-value> </ constant> Mask Checkler, Mask Checker, is declared as re-reluired verifier, so if a field simultaneously Relying on Required and Mask, the Required Checkler must successfully complete it before the Mask checkor application.</p> <p>12.3.3 Range Checkered Range Checker Checks Whether the value is in the range of the specified maximum and minimum: <Field Property = "Priority" Depends = "Required, Integer, Range"> <arg0 Key = "responseform.priority.displayName" /> <var> <var-name> min </ var-name> <var-value> 1 </ var-value> </ var> <var> <var-name> Max </ var-name> <var-value> 4 </ var-value> </ var> </ field> This verifier will successfully be entered in the fields 1, 2, 3, or 4 Next, in practice, the error message will display the maximum and minimum value of the display to help the user to enter correctly. You can use the ARG element to include a reference to MIN and MAX variables in the message: <Field Property = "Priority" Depends = "Required, Integer, Range"> <arg0 key = "responseform.priority.displayName" /> <arg1 name = "Range" key = "$ {var: min}" resource = "false" /> <arg2 name = "Range" key = "$ {var: max}" resource = "false" /> <var> <var> <var -Name> min </ var-name> <var-value> 1 </ var-value> </ var> <var> <var-name> max </ var-name> <var-value> 4 </ var -Value> </ var> </ field> This means that the template of the range is like the following things: errors.range = please enter a value between {1} and {2}. If the Range Verifier is The priority field fails, you will see the following check message: Please enter a value betWeen 1 and 4. Default, the verifier assumes the keyword of the ARG element matches the keyword bundled in the resource, and will use the value of the resource entry Instead of the value of the Key property. (Original:. By default, the validator assumes that the key of an arg element mat hes a key in the resource bundle and will substitute the value of the resource entry for the value of the key attribute) resource = false switch tells the validator Do not modify the use of Value original look.</p> <p>If Values ​​is processed by a Sele T element, you may want to map messages to First and LAST items on the Sele T list: <arg1 name = "range" key = "priority.range.first" /> <arg2 name = "Range "Key =" priority.range.last "/> This means that there is also the following entries in some places: priority.range.first = do-it-now priority.range.last = forget-about-IT in resource bundle (Resource Bundle) Inside, if a check failed, you will be able to see the priority message: please enter a value between do-it-now and forget-about it. 12.3.4 MaxLength Checker MaxLength Check Check a range of high-end, if the length of the field is less than or equal to the max property, it will succeed: <Field property = "Remarks" depends = "maxlength"> <arg0 key = "responseform.remarks.displayName" /> <arg1 name Name = "Maxlength" = "$ {var: maxlength}" resource = "false" /> <var> <var-name> maxlength </ var-name> <var-value> 1000 </ var-value> </ Var> </ field> This field element guarantees that Remarks (possibly a text domain) does not exceed 1000 characters. Note that we pass the length as a parameter to the check message, just like our practices in the Range Verifier. 12.3.5 minlength Checkr MINLENGTH Verifiers Check a range of low-ends, if the length is greater than or equal to the min attribute, it will succeed: <Field Property = "Password" Depends = "Required, MINLENGTH" > <Arg0 key = "logon.password.displayName" /> <arg1 name = "minLength" key = "$ {var: minlength}" resource = "false" /> <var> <var-name> minlength </ var -name> <var-value> 5 </ var-value> </ var> </ field> Field element specifies that password must be input and the length must exceed five characters.</p> <p>12.3.6 Byte, Short, Integer, Long, Float, and Double Cheats These values ​​are the Type.ParsType method for the Value application standard. If an exception is captured, the verifier returns false, otherwise, the verifier is successful. <Field Property = "Amount" Depends = "Required, Double"> <arg0 key = "typeform.amount.displayName" /> </ field> 12.3.7 Date Check Detector Date Checkon Checking Value Describe a correct Date: <Field Property = "Date" depends = "required, date"> <arg0 key = "typeform.date.displayName" /> </ field> Check the standard Locale object of the frame maintenance (java.util .locale) to the date tool, so Result is automatically localized. The datepattern property will pass a standard date style to a Java.Text.SIMPLEDATEFORMAT object. <var> <var-name> DatePattern </ var-name> <var-value> mm / dd / yyyy </ var-value> </ var> Internally, the datepattern property is used in the SimpleDateFormat constructor, It is then used to resolve values: simpleDateformat formatter = new simpledateformat; Date Date = formatter.parse (Value); if the resolution is successful, the verifier is successful. If the datePatternstri T property is set instead, the length is also checked to ensure that a first bit is included in an appropriate case: <var> <var-name> datepatternstri t </ var-name> <var-value> mm / dd / yyyy </ var-value> </ var> DateFormat.short for the user area is not specified in the case of the specified style. If the Struts Locale object is not available, the default local Locale of the server will be used. Setlenient methods are set to False for all date conversions. 12.3.8 ReditCard (Credit Card Number) Verifier Reditcard Verifier Analysis VALUE See if it is a credit card number: <Field Property = "reditcard" depends = "required, reditcard"> <arg0 key = "typeform. Reditcard.displayname" /> </ field> Credit card number contains a parity number, Validation Check this number and other business rules, whether the prefix of the card matches a credit card provider (American Express, Dis over, Master ARD, VISA) and whether the credit card number Whether the length is consistent with the specified provider.</p> <p>12.3.9 Email Verifier Email Checker Checks an expected Email address format using an Extensive to ensure that it is consistent with the specification of the release: <Field property = "email" depends = "required, email"> <arg0 key = "typeform.email.displayName" /> </ field> 12.4 resource bundle (resource bundles) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------- The fundamental use of the verifier is to make the user amend the input and retry. Because that process includes displaying field tags and messages, Struts Validator takes full advantage of Java's localization features and features of the framework support. (Java localization features are included in 13 chapters.) Of course, the framework also needs to provide localized tags for fields. Because Struts resource bundle is provided as a application level resource, Validator can share the same bindings in the framework, so you can set your labels and messages. You only need to increase the default message for custom messages you need to use for verifiers you use and any custom messages you need when you check a special field. 12.4.1 Default Bundle Struts bundle is configured by deployment description (see Chapter 4). It is usually named ApplicationResources.properties or just Application.properties. In our case application, bundles is stored under the / web-inf / sr / java / resource package. Our default Properties file (Java.util.properties is named Application.properties. To support localized files and are named Application_en.properties, Application_es.properties, Application_Fr.Properties, and more. (Again, more about localization, please see 13 chapters.) There is Validator, you don't need any special things to start using the Struts resource bundle, just add any messages you need to, then then submit to Validator Profile resources keywords. If the application will be localized, the keyword for the Field Tag should already exist, you can share them in other parts of the frame, as shown below: <Field Property = "LastName" Depends = "Required"> <arg0 key = " Registrationform.lastname.displayName "/> </ field> 12.4.2 Default Checkler Message (Validator Messages) If a custom message is not provided by the field element, the default message will be used when the verifier fails. . The keyword for the default message of the verifier is determined when it is defined. The convention is to add an ErrorS to use the verifier name as a prefix. The default message suitable for the Required Verifier is then becomes error.Required. This convention is consistent with the Struts <HTML: ERROR> tag for find errors.header and errors.footer entry. Listing 12.5 shows you the keywords and templates that you can add to a basic checkor.</p> <p>Listing 12.5 Factiles for Basic Verifiers # struts Validator Basic Error Messages Errors.Required = {0} is required. Errors.minLength = {0} Annot Be Less Than {1} Characters. Errors.maxlength = {0 Annot Be Greater Than {1} 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. errors.float = {0} Must be a float. Errors.double = {0} Must be a double. errors.date = {0} IS NOTRORS.RANGE = {0} is not in the range {1} through {2}. Errors. reditcard = {0} is not a valid reditcard number. errors.email = {0} is not a valid e -mail address. ------------------------------------- You may notice that there is no suitable ErrorS . Mask's entry, for historical reasons, the definition of the Mask Checker is specified in Errors.INValid instead of Errors.mask. Each verifier message can occupy four alternative parameters, which are specified by the ARG element in the field definition. The first parameter, arg0 or {0}, is usually a keyword for field tags. The verifier will look up the text from the resource bundle to the label, simultaneously, localize the text to the message template. 12.4.3 Custom Verifier Messages A field can also specify a custom verifier message to replace the default message. This phenomenon usually occurs in the case where the Mask checkter will be used, so you can explain what the regular expression is expected.</p> <p>The keyword of the message is given in the MSG element, because more than one verifier will be used by a field, the verifier name is included as the name attribute of the MSG element: <Field Property = "User" depends = "required, mask" > <msg name = "mask" key = "logon.username.maskmsg" /> <arg0 key = "logon.username.displayname" /> <var> <var-name> mask </ var-name> <var- Value> ^ [A-ZA-ZA0-9] * $ </ var-value> </ var> </ field> In the Properties file, we can arrange a key / template: logon.userName as the following description. MASKMSG = {0} Must Be Letters and Numbers, No Spaces. 12.5 Profile --------------------------------- ---- Struts Validator is the strength of the verification is declared in the form of an XML configuration file outside the application source code. Configuration Specifies which field such as the form requires a check, the field requires any special settings to use in other fields. Alternating FormSets can be configured to have different places while covering any location-sensitive checks. (Orternate Formsets CAN BE Configured for Different Locales and Override Any Locale-Sensitive Validations.) All frameworks are configured by XML, including the basic validator included in Pa Kage. You can omit the caliber that you don't need in your application, and you can insert your own custom checkor to let the frames attached to the side. This facilitates creating a flexible package, but combining all of these configured a separate file will cause a lengthy document. As shown in Table 12.3, Struts Validator actually uses two XML files: one is used to set the verifier and the other contains settings for your application. (Note: Struts1.0 uses a single profile.) Table 12.3 Struts Validator configuration file</p> <p>File Name Description Validator-rules.xml Checker Validator.xml Application Check (Validations) This helps a convenient arrangement, so that you can copy a verification rule between applications Standard settings, then customize the validation.xml file, or if you like, you can still combine all the elements into a separate validation.xml file. In Struts1.1, the path to the Validator configuration file is declared in the struts-config.xml file, as shown below: <plug-in lassname = "org.apache.struts.validator.validatorPlugin"> <set-property proty = " Pathnames "Value =" / Web-INF / VALIDATOR-Rules.xml, / Web-INF / VALIDATION.XML "/> </ plug-in> See Chapter 4, you can get more about installing struts validator1.1 components Go to your application message. 12.6 Validator JSP Tags ----------------------------------- Struts Validator Frame Union (optional) JavaScript needs to be used to verify a form of JavaScript to a separate script. You can insert the script into your JSP page via a custom tag, the script will be called when the form is submitted. If the check failed, the script displays an error message window, as shown in Figure 12.1 above, while submitting failed. In addition, the submission success simultaneously controls the Validate method that is transferred to the ACTIONFORM, ensuring that the verification is triggered even if JavaScript is not available. In Listing 12.4, we introduce <JavaScript> tags, simple, this list retains the original <HTML: Erroors> tag. The original <ERRORS> tag can be used to use on the page but ask you to mix tags and messages, and let them get along with you. In addition, if the message is presented in the form of a block, they will run together to a separate paragraph. Under the Struts Validator framework, the error message is shared by the JavaScript checks. In practice, there is a problem with the same tag when the field contracts are in the event. A better way is to use simple messages around. (S) The Struts Validator Tag Library provides additional tags to help solve this very problem, < ERRORSPESENT> or <MessageSpresent> Tag report has any unresolved messages. <message> Mark is working like an item, so your page can cycle throughout the entire column, if there is any required tag entry along the way.</p> <p>(Original: .. So Your Page An Loop Through The Queue, Providing Any Makup Entries 12.6 Re-exhibits the code of the list 12.4, this time the message mark is equipped, the list 12.7 shows the Struts1.1 version Case.</p> <p>Listing 12.6 Contains a login page (struts1.0) <% @ Taglib URI = "/ tags / struts-html" prefix = "html"%> <! - u -> <% @ taglib URI = "/ tags / struts-validator" prefix = "Validator"%> <html> <head> <title> Sign in, please! </ title> </ head> <body> <! -? -> <Validator: Errorspresent> <ul> <! -> <value> <li> <bean: write name = "error" /> </ li> </ validator: errors> </ Ul> </ validator: errorspesent> <! -> <html: form action = "/ logonsubmit" FOCUS = "username" οnsubmit = "validatelogonform (this)"> <table border = "0" width = "100%"> <tr> <trh align = "right"> username: </ th> <td align = "left"> <html: text property = "username" /> </ td> </ TR> <TR> <TH Align = "Right"> Password: </ TH> <TD align = "left"> <html: password property = "password" /> <td> </ tr> <tr> <TD align = "Right"> <html: Submit property = "submit" value = "submit" /> </ td> <TD align = "left"> <html: reset /> </ td> <! -? - > <TD align = "left"> <html: cancel οnclick = "bcancel = true" /> </ td> </ tr> </ table> </ html: form> <! - '-> <validator : JavaScript Formname = "Logonform" /> </ b ODY> </ html> Listing 12.6 Contains the login page (struts1.0) <% @ Taglib URI = "</p> <p>/ tags / struts-html "prefix =" html "%> <! - u -> <% @ Taglib URI =" / tags / struts-validator "prefix =" validator "%> <% @ Taglib URI =" / tags / struts-logic "prefix =" logic "%> <html> <head> <title> Sign in, please! </ title> </ head> <body> <! -> <logic: MessagesPresent> <ul> <! -> <logic: message ID = "error" <li> <bean: write name = "error" /> </ li> </ validator: Messages> </ ul> </ Validator: MessageSpresent> <! -? -> <html: form action = "/ logonsubmit" FOCUS = "username" οnsubmit = "validatelogonform (this)"> <table border = "0" width = "100% > <TR> <TH Align = "Right"> username: </ th> <TD align = "left"> <html: text protection = "username" /> </ td> </ tr> <tr> < TH align = "right"> password: </ th> <TD align = "left"> <html: password property = "password" /> <td> </ tr> <tr> <TD align = "right" > <html: Submit property = "submit" value = "submit" /> </ td> <TD align = "left"> <html: reset /> </ td> <! -> <td align = "Left"> <html: cancel οnclick = "bcancel = true" /> </ td> </ tr> </ table </ html: form> <! - '-> <validator: javascript formname = Logonform "/> </ body> </ html > ------------------------------------- Here are some of the list 12.6 and 12.7 to pay attention to Places: u Because we want to use the Struts Validator tag,</p> <p>So we need to import tag libraries. In Struts 1.1, we also need to import the Logic tag library because it now contains tags we can use here. • The ERROR tag of Struts1.0, or the MESSAGE tag of Struts1.1, let us only leave the HTML on the page and leave the error message outside. If there is no message there, this entry area will be skipped. ? <ERRORS> or <Messages> Mark like an Iterator. These tags expose the messages under each ID ErroRRORS to enable the bean tag to write them in turn (on the page). A JavaScript OnSubmit event is added to the <HTML: Form> tag. This will call our checkman JavaScript When any submission button is pressed or the JavaScript Submit event is triggered? To allow the user to cancel the submission behavior and bypass check, a JavaScript flag can be set. If the BCANCEL property of the 提 交 button is set to True, the Struts Validator will transfer the control directly to the action. 'Finally, but not insignificant, it is current <JavaScript> tag. At runtime, it will be replaced with a Script to combine those JavaScript checkers in the current FORM. That script, like ActionForm, is named after the action-mapping property name, is logonform. Both the basic verifiers provided by the frame include a JavaScript check, if an insertable verifier (12.9) provides a JavaScript check, it is preferably included here. To make the script success, all verbs must be successful. The generated JavaScript follows the ValidatorForm's PAGE attribute, while generating only a page number with a page number less than or equal to a page number of the Form. (Order: The Generated Javascript Observes The Page Property of the ValidatorForm and Will Only Generate Validators for Fields with a page number Equal to or leed Than's form's page number is zero 0. This is useful in multi-page orientation. (See 12.10.1) 12.7 ValidatorForm and ValidatorActionform ------------------------------------------------- Struts 1.1 enables Struts Validator, just follow the initialization settings for Chapter 4 and inherits your ActionForm from ValidatorForm and ValidatorActionform. ValidatorForm matches the Formset name based on the FORMBEAN name. ValidatorActionForm matches the Formset name according to the action-mapping path. In most cases, Struts Validator can completely replace the need to write a Validate method in ActionForm. However, you should still need a validate method that can easily work outside the Validation framework. In most cases, you may need to call the Validator framework first if you pass, and then you can run your own verification. Listing 12.8 will tell you how this work is done.</p> <p>Listing 12.8 with parity login page public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) {// u ActionErrors errors = super.validate (mapping, request); // if (errors == null) errors = new ActionErrors ()? ; If (errors.empty ()) {//? IF (notgood (mapping, request) errors.add (actionerrors.global_error, new actionerror ("errors.notgood", "GoodProperty");} if (Errors. Empty ()) Return Null; return (Errors);} -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --- First, we call ancestrate Validate method, in this case, we call the Validator framework? Because the ancestors may return null, we first need to check NULL. Because we have to run our own validations, if a "not" returns, you may need to send Errors, so we create a new ActionerRors object. If the ancestors return ERRORS, this implementation does not run our validations, although if you feel, you can perform your own checks as it is easy. ? Our sample validation calls a Helper method called NotGood, returns the results of our custom verification. We pass the parameters from the Validate method to confident that notgood knows what all validate knows. 12.8 Localization check ----------------------------------- Validator profile contains a formset element, Formsets is a package that shared a collection of forms set in public areas. Some fields of certain forms do require localization, usually most of them do not need. Struts Validator allows you to localize the selected fields and use the default check for the remaining fields. The default Formset ignores language, country and different properties. Localized fully restricted scope, you can define a format to override just language, or only the country, or cover both when needed. For more information on internationalizing your app, see Chapter 13.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-11710.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="11710" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.066</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'gwuwevknfpA5Tu8RUMU2_2FHKlYfuMDqa0DwokOFtyWoPI9ZE9FFCKqQ4_2FLHckXbaCgWP5Pwj0HitrEdUI'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>