[Struts2 Study Notes (11)] perform input validation on all the methods of action based on the input validation and XML configuration method of action. struts2 Study Notes
In struts2, we can verify all the methods of the action or the specified method of the action.
Two input verification methods are provided for struts2:
1. Use manual coding for implementation.
2. Implementation Based on XML configuration.
1. Use manual coding to implement 1. Manually write code to verify all input methods in the action
By Rewriting the validate () method, the validate () method verifies all methods in the action that are the same as the execute method signature.
When a data verification fails, we should call addFieldError () to add verification Failure Information to fieldErrors of the system.
(To use the addFieldError () method, action can inherit ActionSupport.) If the system's fieldErrors contains failure information,
Struts2 forwards the request to the result named input. In the input view, you can use <s: fielderror/> to display the failure information.
Example of validate:
Form submission content:
<Formaction = "$ {pageContext. request. contextPath}/person/manage_update.action "method =" post "> User name: <input type =" text "name =" username "/> cannot be blank <br/> mobile phone number: <input type = "text" name = "mobile"/> it cannot be blank and must comply with the mobile phone number format 1, 3/5/8, there are nine numbers <br/> <input type = "submit" value = "submit"/> </form>
Verification Code:
Package cn. lc. action; import java. util. regex. pattern; import com. opensymphony. xwork2.ActionContext; import com. opensymphony. xwork2.ActionSupport; public class PersonAction extends ActionSupport {private String username; private String mobile; // omit the get/set method/** here is the verification method */public String update () {ActionContext. getContext (). put ("message", "updated successfully"); return "message";} public String save () {ActionContext. getCont Ext (). put ("message", "saved successfully"); return "message" ;}@ Overridepublic void validate () {// all methods in the action are verified if (this. username = null | "". equals (this. username. trim () {this. addFieldError ("username", "username cannot be blank");} if (this. mobile = null | "". equals (this. mobile. trim () {this. addFieldError ("mobile", "mobile phone number cannot be blank");} else {if (! Pattern. compile ("^ 1 [358] \ d {9} $ "). matcher (this. mobile ). matches () {this. addFieldError ("mobile", "Incorrect mobile Phone Number Format ");}}}}
Configuration file:
<struts> <package name="person" namespace="/person" extends="struts-default"> <action name="manage_*" class="cn.lc.action.PersonAction" method="{1}"> <result name="input">/index.jsp</result> <result name="message">/WEB-INF/page/message.jsp</result> </action> </package></struts>
After verification fails, the request is forwarded to the input View:
<Result name = "input">/WEB-INF/page/addUser. jsp </result>
On the addUser. jsp page, use <s: fielderror/> to display the failure information.
2. Manually write the code to verify the input of the specified action Method
By using the validateXxx () method, validateXxx () only verifies the method named Xxx in the action. The first letter of Xxx must be in uppercase. When a data verification fails, we should call the addFieldError () method to add verification failure information to the fieldErrors of the System. (to use the addFieldError () method, action can inherit ActionSupport ), if the system's fieldErrors contains Failure Information, struts2 forwards the request to the result named input. In the input view, you can use <s: fielderror/> to display the failure information.
Example of validateXxx () method:
Public class PersonAction extends ActionSupport {private String username; private String mobile; // get/set Method public String update () {ActionContext. getContext (). put ("message", "updated successfully"); return "message";} public String save () {ActionContext. getContext (). put ("message", "saved successfully"); return "message";} public void validateUpdate () {// if (this. username = null | "". equals (this. username. trim () {thi S. addFieldError ("username", "username cannot be blank");} if (this. mobile = null | "". equals (this. mobile. trim () {this. addFieldError ("mobile", "mobile phone number cannot be blank");} else {if (! Pattern. compile ("^ 1 [358] \ d {9} $ "). matcher (this. mobile ). matches () {this. addFieldError ("mobile", "Incorrect mobile Phone Number Format ");}}}}
The configuration file has not changed. The form submission code has not changed!
3. input verification process
1. The type converter performs type conversion on the Request Parameters and assigns the converted value to the attribute in the action.
2. If an exception occurs during type conversion, the system saves the exception information to ActionContext. The conversionError interceptor adds the exception information to fieldErrors. No matter whether the type conversion is abnormal or not, it will go to step 1.
3. The system uses reflection technology to call the validateXxx () method in action. Xxx is the method name.
4. Call the validate () method in action.
5. After the preceding four steps, if fieldErrors in the system has an error message (that is, the size of the Set storing the error information is greater than 0), the system automatically forwards the request to the view named input. If fieldErrors in the system does not have any error information, the system will execute the processing method in the action.
II. Implementation Based on xml file configuration 1. the XML configuration method is used to verify input of all actions (1) when the XML configuration method is used to verify input, the action also needs to inherit the ActionSupport and provide the verification file, the verification file and action class are placed in the same package, the file name format is: ActionClassName-validation.xml, where ActionClassName is the simple class name of action,-validation is a fixed writing. If the Action class is cn. itcast. UserAction, the file name should be: UserAction-validation.xml. Below is the validation file template :( PersonAction-validation.xml file as follows :)
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE validators PUBLIC "-// OpenSymphony Group // XWork Validator 1.0.3/EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd"> <validators> <field name = "username"> <field-validator type =" requiredstring "> <param name =" trim "> true </param> <message> the user name cannot be blank! </Message> </field-validator> </field> <field name = "mobile"> <field-validator type = "requiredstring"> <message> the mobile phone number cannot be blank! </Message> </field-validator> <field-validator type = "regex"> <span style = "white-space: pre "> </span> <param name =" expression "> <! [CDATA [^ 1 [358] \ d {9} $]> </param> <span style = "white-space: pre "> </span> <message> the mobile phone number format is incorrect! </Message> <span style = "white-space: pre"> </span> </field-validator> </field> </validators>
(2) <field> specifies the attribute to be verified in the action, <field-validator> specifies the validator. The requiredstring specified above is provided by the system, the system provides validators that meet most of the verification requirements, and the definitions of these validators can be in the xwork-2.x.jar of com. opensymphony. xwork2.validator. default under validators. in xml.
<Message> This is the prompt message after verification failure. If you want to internationalize the message, you can specify the key attribute for the message. The key value is the key in the resource file.
In this verification file, to verify the string-type username attribute in the action, you must first call the trim () method to remove spaces and then determine whether the username is empty.
(3) List of validators provided by struts2
The system provides the following Checker: required (required checker, requires that the field value cannot be null) requiredstring (required string checker, requires that the field value cannot be null, And the length is greater than 0, by default, spaces before and after the string are removed) stringlength (String Length checker, requires that the field value must be within the specified range, otherwise the verification fails, the minLength parameter specifies the minimum length, the maxLength parameter specifies the maximum length. The trim parameter specifies whether spaces before and after the string are removed before the field is verified. The regex (Regular Expression validator) checks whether the verified field matches a regular expression. the expression parameter specifies the regular expression, and the caseSensitive parameter specifies whether the regular expression is case sensitive when matching. The default value is true) int (integer validator, which requires that the field integer value must be within the specified range, min specifies the minimum value, max specifies the maximum value) double (double-precision floating point number checker, requires that the field's double-precision floating point number must be within the specified range, min specifies the minimum value, max specifies the maximum value) fieldexpression (field OGNL expression checker, the field must satisfy an ognl expression. The expression parameter specifies an ognl expression. The logic expression is evaluated based on ValueStack. If the return value is true, the value is verified. Otherwise, the value is not verified. email (email address checker, it is required that the field value be a valid email address if it is not empty. The url (website verifier) must be a valid url address if the field value is not empty) date (date validator, requires that the field's date value be within the specified range, min specifies the minimum value, max specifies the maximum value) conversion (conversion validator, specified when the type conversion fails, error Message) visitor (used to verify the compound attribute in action, it specifies a validation file used to verify the attribute in the compound attribute) expression (OGNL expression validator, the expression parameter specifies the ognl expression, this logical expression is evaluated based on ValueStack. If the return value is true, the verification succeeds. Otherwise, the verification fails. This validator cannot be used in the style configuration of the field validator)
(4) Example
Required: <field-validator type = "required"> <message> the gender cannot be blank! </Message> </field-validator> requiredstring mandatory string checker <field-validator type = "requiredstring"> <param name = "trim"> true </param> <message> The user name cannot be blank! </Message> </field-validator>
Email: email address checker <field-validator type = "email"> <span style = "white-space: pre "> </span> <message> invalid email address </message> </field-validator> regex: regular expression validator <field-validator type = "regex"> <param name = "expression"> <! [CDATA [^ 1 [358] \ d {9} $]> </param> <message> incorrect mobile phone number format! </Message> </field-validator> stringlength: string Length checker <field-validator type = "stringlength"> <param name = "maxLength"> 10 </param> <param name = "minLength"> 2 </param> <param name = "trim"> true </param> <message> <! [CDATA [product name should be 2-10 characters in length]> </message> </field-validator>
Int: integer validator <field-validator type = "int"> <span style = "white-space: pre "> </span> <param name =" min "> 1 </param> <span style =" white-space: pre "> </span> <param name =" max "> 150 </param> <span style =" white-space: pre "> </span> <message> the age must be between 1 and </message> </field-validator> field OGNL expression validator <field name =" imagefile "> <span style = "white-space: pre "> </span> <field-validator type =" fieldexpression "> <span style =" white-space: pre "> </spa N> <param name = "expression"> <! [CDATA [imagefile. length () <= 0]> </param> <span style = "white-space: pre "> </span> <message> the file cannot be blank </message> <span style =" white-space: pre "> </span> </field-validator> </field>
2. Some methods of action are verified based on XML configuration.
(1) When the validation file is named ActionClassName-validation.xml, it will implement input verification for all the processing methods in the action.
If you only need to verify an action Method in the action, then the validation file name should be: ActionClassName-ActionName-validation.xml, where ActionName is the name of the action in struts. xml.
For example, the following configurations are often used in actual applications:
<action name="user_*" class="cn.itcast.action.UserAction" method="{1}“ ><result name="success">/WEB-INF/page/message.jsp</result><result name="input">/WEB-INF/page/addUser.jsp</result></action>
There are two solutions for UserAction:
public String add() throws Exception{ ....}public String update() throws Exception{ ....}
To validate the add () method, the validation file is named: UserAction-user_add-validation.xml
To validate the update () method, the validation file is named: UserAction-user_update-validation.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE validators PUBLIC "-// OpenSymphony Group // XWork Validator 1.0.3/EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd"> <validators> <field name = "username"> <field-validator type =" requiredstring "> <param name =" trim "> true </param> <message> the user name cannot be blank! </Message> </field-validator> </field> <field name = "mobile"> <field-validator type = "requiredstring"> <message> the mobile phone number cannot be blank! </Message> </field-validator> <field-validator type = "regex"> <param name = "expression"> <! [CDATA [^ 1 [358] \ d {9} $]> </param> <message> incorrect mobile phone number format! </Message> </field-validator> </field> </validators>
3. Some features of XML-based Validation
When a validation file provides ActionClassName-validation.xml and ActionClassName-ActionName-validation.xml rules for an action, the system looks for the validation file in the order below:
1. AconClassName-validation.xml
2. ActionClassName-ActionName-validation.xml
When the system finds the first check file, it will continue to search for the subsequent check files. When it finds all the check files, it will summarize all the validation rules in the check file, then it is applied to the verification of the action method. If the verification rules specified in the two verification files conflict, only the validation rules in the following files are used.
When action inherits another action, the validation file of the parent action is first searched.
Assume that UserAction inherits BaseAction:
<Action name = "user" class = "cn. itcast. action. UserAction" method = "{1}">
</Action>
Access the above action, the system first search for the parent class of the validation file: BaseAction-validation.xml, BaseAction-user-validation.xml, and then search for the subclass of the validation file: UserAction-validation.xml, UserAction-user-validation.xml. The validation rules applied to the preceding actions are the sum of the four files.
Note: Please indicate the source for reprinting!
Struts2 verifies all action methods based on XML Configuration
Your regular expression should be wrong.
Try this! [CDATA [^ [1] [3-8] + \ d {9}]
In Struts2, a specified method is redirected from one action to another (there are many methods in this action). How to configure xml?
First action configuration: return "other" in the execute method ";
<Action name = "myAction" class = "com. test. action. MyAction">
<Result type = "redirectAction" name = "other"> write the url path of another action, relative path. </result>
</Action>
Second action configuration,
<Action name = "otherAction" class = "com. test. action. OtherAction" method = "other">
<Result name = "success"> result page </result>
</Action>