Struts Validator Development Guide

xiaoxiao2021-03-06  65

Struts Validator Development Guide

Make Struts to Validator .. 1

Validator-rules.xml file .... 2

Validator.xml file .... 2

Required Validator .. 3

Mask Validator .. 3

Range Validator .. 4

Maxlength Validator .. 4

MINLENGTH Validator .. 5

Email Validator .. 5

Writing of form bean .... 5

Struts-config.xml file configuration .... 5

Capture error message in JSP page .... 6

Capture the error message of the server ... 6

Capture the wrong information of JavaScript ... 6

Write extended struts validator check password input .... 7

1. Write a verifer (Validator) to implement a consistent check of two fields in Form: 7

2. Write a Validator-Rules file to add a custom checkor configuration: 8

3. Write a JSP page ... 9

4. Write the validator.xml configuration file: 10

Make struts to support Validator

To use the Validator feature in the Struts project, you first need to configure the Struts project to support the Validator framework. Struts allows the Struts project to support the Validator. This Plugin is provided by Struts, and users can also develop their own Validator. Plugin.struts The default Plugin is:

Org.apache.struts.validator.validatorPlugin.

The user must configure this PLUGIN in the struts-config.xml file to support the Struts project to support the Validator. The configuration method is relatively simple, open the struts-config.xml file through any text editor, add the following code at the end of this file, Restarting the J2EE server can be supported for Validator.

In the JBUILDER development environment, you can support the Struts project to support the Validator framework by the following method.

1. Right-click the Web project in the project manager (WebModule in our project).

2. Select the "Properties ..." menu item for the menu.

3. Select the "Web" node in the left tree structure of the pop-up dialog.

4. Check "Sturts in the" JSP / Servlet Frameworks "box on the right

1.1 "

The "Validation" child node under the node and the "struts" node.

5. Click the "OK" button to complete the configuration.

6. Check the struts-config.xml file, you can see the Validator Plugin in the configuration file.

Validator-rules.xml file

Validator-rules.xml file is the definition file for the verifier. Specifies the basic information of each checker and the JavaScript code that executes the verification. Struts provides fourteen verifiers by default, these verifiers can meet us The vast majority of input check requirements encountered in the usual project development. If these validers do not meet the user's verification requirements, then we can also develop our own verifier. Our project owner implements a check password Consistency Validator.

Struts provides verification comprises Required Validator, Requiredif Validator, MinLength Validator, MaxLength Validator, Mask Validator, Byte Validator, Short Validaotr, Integer Validator, Long Validator, Float Validator, Double Validator, Date Validator, Range Validator, IntRange Validator, FloatRange Validator, CrediteCard Validator, Email Validator and other verifiers. Behind I will tell some of the more commonly used verifiers .valiDator.xml file

Validator.xml file Use the verification rule for each of the JSP Forms that users need to be verified, this file is the file we need to configure in the Struts project development. The root node of this file is , the

child of the node under the root node corresponds to the development of the JSP file is the defined form mark, and the definition of the Form Bean in this struts-config.xml One node consists of multiple nodes, each node has a structure as follows:

minlength 8 secondproperty Password2

One of the a field, the tag of the indicates the FORM BEAN's field name, this name is in the struts-config.xml file. The name of the name defined. Depends attribute illustrates that this field relies on the verification of the verifier, you can use multiple verifiers, and the comma is separated between each verifier. tag Description When this field The error message provided to the user is not the verification .Name property specifies the corresponding verifier, the Key property specifies the error message defined in the ApplicationResources.properties file. and are passed to the verification The parameter of the device. The tag defines the name and parameter value of the parameters. The above example illustrates the Password field by Required, minLength, Twofields Verifier. Specify this Field can't be empty, and the minimum length cannot be Less than 8 is, and must be the same as the field named Password2 in the same form. If the user's input cannot meet these requirements, the verboator will throw an exception. How to configure each other in this configuration file below The verifier implements the check of multi-medium type Field in the Form.

Required Validator

This verifier is used to verify the Form's input data cannot be empty. If a Form's Field relies on this verifier, if the user does not enter the input data corresponding to this Field in the Form, the Required verifier will Trigger an Exception, this Exception error message can be captured on the page or the server.

example:

The above example illustrates that the verification rule of the TEST field cannot be empty, and the corresponding definition information in ApplicationResources.properties may be the following case:

Test.Testfield.DisplayName = Test field # The key = "test.testfield" defined in the tag is in the tag. Test.Required = {0} can not be empty, please re-enter. # 在 above the Tag corresponding this information

If the Validator checks that the user does not enter the Test this field, the information corresponding to the test.testfield is passed to the verifier as Test.Required parameters. If the error message is captured in the JSP page, the error message will be below. This form:

"The test field can't be empty, please re-enter"

Mask Validator

Mask Validator checks if the data entered by the user is in accordance with certain rules, and this rule is defined by the developer in the validator.xml file.

example:

Mask

^ 0 / d * $

The above tag illustrates that the second parameter of this check is the value defined in the name of the tag. The value of illustrates that this field must be started with the number 0, A string of the end of any number of characters.

Range Validator

This verifier calibration field is within a number range.

example:

min 1 max 100

Range Validator requires three parameters (arg), the first parameter arg0 is the maximum and minimum of the name, the second and third parameters specified by the specified range, respectively, respectively, MAX and MIN.

Maxlength Validator

The MaxLength Verifier checks the maximum length of a string, it requires two parameters, the Arg0 description field name, the arg1 description maximum length.

example:

maxlength 8

MINLENGTH VALIDATOR This verifier is similar to the MaxLength Validator, the parameter, the verification rule is the same, but the number of variables as the parameter is MINLENGTH.

minlength 8

Email Validator

This verifier checks the email field. When the email address entered by the user is not legal, the verifier throws an exception.

example:

< Arg0 key = "Test.email" />

Writing of Form Bean

The Form Bean to be automatically verified using the Struts Validator Framework cannot inherit from ordinary actionform, must inherit from ValidatorForm or ValidatorActionform. Our project groups are inherited from ValidatorForm.

ValidatorForm is the corresponding verifier corresponding to the current Form's call according to the Action of the Struts-Config.xml file, so the name attribute (name) of element in validator-rules.xml should be The Name property value matches.

ValidatorActionForm uses the path property of the action in struts-config.xml, so the value of the Path property should match the name attribute of the FORM in Validator.xml.

Struts-config.xml configuration configuration

To use the Validator Framework, you must also work with the corresponding configuration in the struts-config.xml file. In addition to the configuration Validator Plugin, you need to configure the Action of the FORM you need to verify. Main There are two places that need to be configured, one is the INPUT property, one is the value of Validate properties. INPUT attribute must specify the path to the JSP page containing the verification form, so that when Struts's verification framework is failed You can re-guided the original page to re-enter the .validator property is a Boolean type property, you must set to TruE Struts will only start the auto check mechanism. Capture the error message in JSP page

The Validator's checking mechanism can define the server to check or verify the browser side via JavaScript. Both different ways have a big difference when writing in the JSP page.

Capture the error message of the server

The error message to capture the server check is relatively simple. You can display an error message in the page only in the JSP page, which can also customize the display style.

  • Reports the cause and brief description of the user's error occurrence through the information defined in the ApplicationResources.properties file.

  • It is shown to display the specific error message generated by the Validator framework.

    Capture the wrong information of JavaScript

    To capture the error message generated by JavaScript First, let's generate the JavaScript code generated by the JSP page and let the submit button trigger the corresponding check function when the user clicks the submission button. Implementation method is as follows:

    First let JSP trigger the calibration function and use this HTML code:

    >

    Where Action specifies the action of this form, this is no different from ordinary Form, the onSubmit property specifies the verification function, its rules are: return space Validator ValidatorForm name (this)

    Note that such a combination rule cannot be changed, otherwise the page error can not be verified. Please pay attention to the first letter of the ValidatorForm's name must be capitalized, regardless of whether it is capitalized in the struts-congfig.xml file. Here, you must use it as uppercase letters.

    Then you have to generate a JavaScript code that you can implement in the JSP page. This step is also very simple, just add the following sentence at the end of the JSP page:

    Where the FormName's name is consistent with the configuration in the struts-config.xml file. Samples of STATICJAVAScript True will use the JavaScript code to check (these JavaScript code is automatically generated by the Validator framework of Struts, we only You need to configure the validator.xml file), and StaticJavaScript When Validator will check with the server code, the check code of these serve doesn't need to be written. Written Struts Validator check password input

    Using Struts's Validator check page Form is consistent, it is generally used in the check password. When the user enters two passwords, it is necessary to verify whether the user's two inputs are consistent. If it is inconsistent, it needs to be reported. Implement this function The steps are as follows:

    1. Write a Validator to implement a consistent check of two fields in Form:

    Package cn.com.syni.net800114.validator;

    Import org.apache.commons.validator.validatorutil; import org.apache.commons.validator.field; import org.apache.commons.validator.Validator; Import Org.Apache.commons.validator.GenericValidator;

    Import org.apache.struts.action.actionerro; import org.apache.struts.validator.resources;

    Import javax.servlet.http.httpservletRequest;

    public class ValidationUtil {public static boolean validateTwoFields (Object bean, ValidatorAction va, Field field, ActionErrors errors, HttpServletRequest request) {String value = ValidatorUtil.getValueAsString (bean, field.getProperty ()); String sProperty2 = field.getVarValue ( "secondProperty "); String value2 = validatorutil.getValueAsstring (bean, sproperty2);

    IF (! genericvalidator.isblankornull (value) {try {if (! value.equals (value2)) {Errors.Add (Field.getKey (), Resources.getActionError (Request, Va, Field); Return False;} } Catch (Exception E) {Errors.Add (Field.getKey (), Resources.getActionError (Request, Va, Field)); Return False;}} Return true;}} 2. Write a Validator-Rules file, add a self Define the configuration of the checker:

    Field.value; secondValue = secondfield.value;}}}}} {if (i == 0) {FOCUSFIELD = Field;} Fields [i ] = OTWOFIELDS [X] [1]; bvalid = false;} }}}}} {FOCUSFIELD.FOCUS (); Alert (Fields.Join ('/ n'));}}}}]> 3. Write JSP page

    The Form is included in the field to be custom verified. Here is the two password type INPUT, the verifier will match the two fields entered by the user. If it is inconsistent, you will tell the user by pop-up dialog box:

    <% @ Taglib URI = "/ Web-INF / STRUTS-Bean.TLD" prefix = "bean"%> <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%> <% @ Page ContentType = "Text / HTML; Charset = GBK"%> regiestation </ title> </ head> <body> <html: form action = "/ registration. Do "onSubmit =" Return ValidateRegistry (this);> <bean: message key = "userform.password" /> <html: password print = "password" /> <br> <bean: message key = "Userform.password2 "/> <html: Password property =" password2 "/> <br> <html: Submit property =" submit "value =" submit "/> <br> <html: reset value =" reset "/> </ html : form> </ body> <html: javascript formname = "registry" staticjavascript = "true" Dynamicjavascript = "true" /> </ html: html> where <html: form action = "/ registrationAction can" onSubmit = "Return ValidatorRegistry (this);" Description This window needs to use Struts Validator to verify, the action property specifies the action corresponding to this JSP page, the onSubmit property specifies the actionform bean corresponding to this page checkout, its rule is "Return Validator FormBeanName (this); ", the example here means that this page is /regiestationAction.do, which corresponds to the Action Form name as registry (note, such as If the Actionform's name is registry in the struts-config.xml file, the first letter is also capitalized here, otherwise it is wrong.</p> <p>The final penultimate line <HTML: JavaScrip> tag Description To use Java Script to make a client check, the FormName property specifies the name of the Action Form, this name is consistent with the configuration in the struts-config.xml file, strictly sinking StaticJavaScript and DynamicJavascript specify whether to check with static or dynamic JavaScript code.</p> <p>4. Write the validator.xml configuration file:</p> <p><form name = "registration"> <field proteth = "password" depends = "required, twofields"> <msg name = "required" key = "errors.required" /> <msg name = "Twofields" key = "ERRORS .twofields "/> <arg0 key =" userform.password "/> <arg1 key =" userform.password2 "/> <var> <var-name> secondproperty </ var-name> <var-value> Password2 </ VAR-VALUE> </ var> </ field> </ form> Here you should pay attention to the <var-name> attribute, you want to consistent with the code in the verification method in ValidatorUtil.java, otherwise Validatorutil.java cannot correctly The <var-value> property specifies the check field referred to in this verification field. The above configuration code description To check the Password field in the Form, it must be consistent with the other field called Password2. Action should Written content:</p> <p>Public ActionerRors Validate (ActionMapping Mapping, HttpServletRequest Request) {ActionerRors Errors = New ActionerRORS ();</p> <p>Return super.validate (mapping, request);</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-84017.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="84017" 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.054</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 = 'ORNEwge48amXp8pIqEVLgxCROmTJZSuVtsRORL3Gs5MtPJdevO_2BO2U5BeQrOPKLZUoML6RXhBvwwdsc8zJnGaQ_3D_3D'; 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>