STRUTS2 input checksum validate input check mode

Source: Internet
Author: User

I. There are a large number of view pages in a Web system project that require users to enter a lot of data themselves. There are many types of these data. In order to prevent some customers from malicious input and malicious damage to Web projects, you must introduce input validation, like the Windows operating system firewall to filter out some of the junk data, blocking outside the web system. Next, let's introduce the Validate input check method:

1.validate method for input verification: here is a simple user registration function. This article introduces how to use the Validate method to input and verify the type data such as numbers, strings, dates and so on:

(1). First, create a new STRUTS2 project Inputvalidate, the project structure is as follows:




(2). Create a new registration page, the register.jsp page, for entering the checksum input data, the code is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><%@ taglib uri= "/struts-tags" prefix= "s" %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


(3). Create a new action class, Registeraction class, with the following code:

Package Com.gk.action;import Java.util.date;import Com.opensymphony.xwork2.actionsupport;public class Registeraction extends Actionsupport {private string Username;private string Password;private string password1;private Date birthday;private string mobile;private int age;public string GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String GetPassword1 () {return password1;} public void SetPassword1 (String password1) {this.password1 = Password1;} Public Date Getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;} Public String Getmobile () {return mobile;} public void Setmobile (String mobile) {this.mobile = mobile;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Execute () {return SUCCESS;} public void Validate () {if (getusername () = = nulL | | GetUserName (). Trim () equals ("")) {Addfielderror ("username", "Enter user name");} if (GetPassword () = null | | GetPassword (). Trim (). Equals ("")) {addfielderror ("password", "Please enter password");} if (getPassword1 () = null | | getPassword1 (). Trim () equals ("")) {Addfielderror ("Password1", "Please enter a confirmation password");} if (!getpassword (). Equals (GetPassword1 ())) {Addfielderror ("password", "Password and input password inconsistent");} if (getbirthday () = = null) {Addfielderror ("Birthday", "Enter birthday Date"),} else if (Getbirthday (). After (new Date ())) { Addfielderror ("Birthday", "Please do not enter a future date"); if (Getmobile (). Length ()! = one) {Addfielderror ("mobile", "Please enter the correct mobile number");} if (Getage () < 1 | | getage () > +) {addfielderror ("age", "Please enter correct ages");}}}


(4). Then configure the Struts.xml file, successfully jump to the success.jsp page, the code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd ">        <struts><constant name=" Struts.enable.DynamicMethodInvocation "value=" true "></constant><constant name=" Struts.devmode "value= "True" ></constant><package name= "input" namespace= "/" extends= "Struts-default" ><action name= " Register "class=" com.gk.action.RegisterAction "><result name=" Success ">/success.jsp</result>< Result name= "Input" >/register.jsp</result></action></package></struts>


(5). Next attach the success.jsp code, which is used to output the information after successful registration:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><%@ taglib uri= "/struts-tags" prefix= "s" %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


(6). Deploy this project to the Tomcat server, open the Tomcat server, enter in the Address bar: http://localhost:8083/InputValidate/register.jsp, run the following:

Do not enter any data, click the Register button as shown:


When you enter a password that is inconsistent and the date of birth is not valid, as shown:


(7). Explain the above code:

-struts2 the most basic approach to input validation is to inherit the Actionsupport class in each action and override its input validation method validate (). The Registeraction code in the example above shows that all error messages that do not conform to the input check rule are added to the form error message by another method Addfielderror method in the Actionsupport class, depending on the various checks entered on the page. and is displayed on the page where the data is entered, and no more action is navigated to the registration success page. Struts.xml also defines a result with the name "input", which indicates that all error messages for input failures are navigated to a specific page. The above example defines this particular page as a data entry page.

-Read the Registeraction code again, and you can see that there are many if statements written in the Validate method, and each of the IF statements has an input checksum for a field in the form. Call the Addfielderror method if you find a non-conforming input validation rule. There are two parameters in the method, and the first parameter is the field name in the form, where all names and the contents of the Name property of each field in the page of the input data are the same. Otherwise Struts2 is unable to find the specific error message for which field. These are displayed in a specific page that was previously mentioned when the input checksum failed.

The individual if statements in the-validate method determine whether the input data for each field in the form conforms to the rules for input validation, which are also defined by the developer according to the specific business logic. such as whether the data is entered, whether the birthday information entered before the current date, and so on. It is also possible to find that these fields are not type-converted, but some of the field types in the action have become some of the basic types of java. such as the Birthday field, when the page is entered as a string, in the action has become the date type in Java. The data entered on the page has been converted from the string type to the Java type specified in the action.

-When entering birthdays because the Struts2 is converted by a built-in type converter, the conversion fails so prompt invalid field value for field "birthday" information.




2.validateXXX method for Input validation: Here we modify some of the code in the Inputvalidate project above to see how the ValidateXxx method can be used to validate a particular method in the action.

(1). First, modify the register.jsp page of the Inputvalidate project, except that the Action property of the form is changed to register!register.action, that is, the action is called dynamically, modified as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><%@ taglib uri= "/struts-tags" prefix= "s" %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


(2). Then modify the Registeraction this class, which wrote a method register and Validateregister method, where the mobile phone number used in the regular expression to verify the correctness of the mobile phone number, modified code as follows:

Package Com.gk.action;import Java.util.date;import Com.opensymphony.xwork2.actionsupport;public class Registeraction extends Actionsupport {private string Username;private string Password;private string password1;private Date birthday;private string mobile;private int age;public string GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String GetPassword1 () {return password1;} public void SetPassword1 (String password1) {this.password1 = Password1;} Public Date Getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;} Public String Getmobile () {return mobile;} public void Setmobile (String mobile) {this.mobile = mobile;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Register () {return SUCCESS;} public void Validateregister () {if (getusername() = = NULL | | GetUserName (). Trim () equals ("")) {Addfielderror ("username", "Enter user name");} if (GetPassword () = null | | GetPassword (). Trim (). Equals ("")) {addfielderror ("password", "Please enter password");} if (getPassword1 () = null | | getPassword1 (). Trim () equals ("")) {Addfielderror ("Password1", "Please enter a confirmation password");} if (!getpassword (). Equals (GetPassword1 ())) {Addfielderror ("password", "Password and input password inconsistent");} if (getbirthday () = = null) {Addfielderror ("Birthday", "Enter birthday Date"),} else if (Getbirthday (). After (new Date ())) { Addfielderror ("Birthday", "Please do not enter a future date"); if (Getmobile (). IsEmpty ()) {Addfielderror ("mobile", "cell phone number is not empty"),} else if (!getmobile (). Matches ("\\d*")) { Addfielderror ("mobile", "Phone number error");} else if (getmobile (). Length ()! = one) {Addfielderror ("mobile", "Please enter the correct mobile number");} if (Getage () < 1 | | getage () > +) {addfielderror ("age", "Please enter correct ages");}}}


(3). Other remains unchanged, redeploy this project and turn on the server, do not enter any data, click the Registration button, its address bar changes, such as:



Password input inconsistency and birthday type conversion failed, the phone number is incorrect, as shown in:


(4). Explanation of the above code:

In addition to the Validate method, the

-struts2 has 1 validatexxx methods for input validation of various fields of the method for a particular method in the action. where xxx is the specific method name. In this example, a register method is defined that is similar to the Execute method in the previous section as a simple navigation. However, there is no validate method in the Registeraction, instead of the Validateregister method.
Note: If you use the Validateregister method, it is best not to use the Validate method again. Although the contents of the two methods are identical to those in the previous section of the sample code, the Validate method verifies the input checksum of all the methods in the action, and the Validateregister method verifies only the Register method. Therefore, both cannot be reused, and both use results that result in the validation of two methods. The order of execution is first validateregister after validate. If the Validateregister method has a special input checksum, it will be "overwritten" by the Validate method, so that the intended input checksum is not achieved. The
-validateregister method contains the same definition of the IF statement and the Validate method in the previous section. This is just as an example so the contents of the two methods are the same, and can actually be different from the contents of the Validate method in the previous section for the Specific form field input check in the Register method. The
-  adds Struts2 label Fielderror to the view interface of the data entry. There is also an error message displayed on the header of the form. This is actually related to the Struts2 check order.

The previous description of the Validateregister method and validate method also describes the execution of the two check order is first validateregister after validate. Actually after the form is submitted in the view interface. The input check order is in the following order:
 Find out if there is a ValidateXxx method in the action. If any, the method is executed. The error message generated by the officer is placed in the Actioncontext object.
 Find out if there is a validate method in the action. If any, the method is executed. The error message generated by the officer is placed in the Actioncontext object.
 Find out if the view interface has a fielderror label definition. If any, return to the view with result "input". The error message for the input checksum in the Actioncontext object is also displayed in the view.


The input check order of the STRUTS2 is executed according to the above instructions, which is also a better illustration of how the Validateregister method and the Validate method coexist in the action when the input check is performed.


(5). Modified Inputvalidate Project: http://download.csdn.net/detail/u012561176/8911561




3. The above content is only for your study reference, write not good, please forgive me, if there are errors, please point out, thank you!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Struts2 input checksum validate input check mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.