Input Validation in struts2_12_struts2

Source: Internet
Author: User

Input Validation in struts2_12_struts2

(1) manual code writing for verification:

By Rewriting the validate () method, the validate () method verifies all the methods in the action that are the same as the execute method signature. When a data verification fails, you should call addFileError () method to add verification failure information to the fieldErrors of the system (to use the addFileError () method, action can inherit actionSupport). If the system's fileError contains failure information, struts2 forwards the request to the result named input and redirects back to the logon page. the information displayed when the jsp view is successful.

Use tags on the index. jsp page The error message is displayed.

1) code in struts:

 
  
   
    /index.jsp
   
   
    /show.jsp
   
  
 

2) methods in the Action class:

Public class HelloAction extends ActionSupport {private String username; private String mobile; public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getMobile () {return mobile;} public void setMobile (String mobile) {this. mobile = mobile;} public String update () {ActionContext. getContext (). put ("message", "updated successfully"); return "success "; } Public String save () {ActionContext. getContext (). put ("message", "saved successfully"); return "success";} public void validate () {// all methods 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 ");}}}}

3) enter the code in index. jsp on the page:

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib uri ="/struts-tags "prefix =" s "%>
 Input checkout
 
 
 
 

4)Code in show. jsp at the display layer:

${message }

Note:If the Interception Method in the Action is written

  public void validateMethodName() {}

In this case, only this method in action is verified.

When the validate () method and validateMethodName () method exist in the action, the validateMethodName () method is called first, and then the validate () method is called.

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 the execution of the type converter, the system saves the exception

In ActionContext, The conversionErrors interceptor adds the exception information

In fieldErrors, no matter whether the type conversion is abnormal or not, the third step is involved.

3> the system uses the reflection technology to call the validateMethodName () method in action.

If no value exists, the validate () method in the action is called.

4> after the above steps, if fieldErrors in the system has an error message (that is, the error message is stored)

The size of the set is greater than 0). The system automatically forwards requests to the view named input. If the system

FieldErrors in does not have any error information. The system will execute the processing method in the action.

(2) validate the action based on the XML configuration method

1. Input Validation for all Action methods:

When using XML-based configuration method for verification, Action must also inherit ActionSupport, and provide the verification file and Action class in the same package, the file name format is: ActionClassName-validation.xml, where ActionClassName is a simple class name, -validation. xml is a fixed syntax. Fixed format of verification file:

The Struts. xml file, index. jsp file, and show. jsp file are the same as those in (1.

1)Code in HelloAction:

Public class HelloAction extends ActionSupport {private String username; private String mobile; public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getMobile () {return mobile;} public void setMobile (String mobile) {this. mobile = mobile;} public String update () {ActionContext. getContext (). put ("message", "updated successfully"); return "success";} public String save () {ActionContext. getContext (). put ("message", "saved successfully"); return "success ";}}

2) Verification Code:

  
     
          
               
    
     
The user name cannot be blank!
            
       
      
          
               
    
     
The mobile phone number cannot be blank!
            
           
        
    ^1[358]\d{9}$     
    
     
Incorrect mobile phone number format!
    
       
  
 

Note: Multiple verification entries can be used for the same attribute. Put multiple verification entries in the same

. Attribute to be verified in the Action, Specify the validator. the validator requiredstring indicates that this attribute is a required string.

The system provides validators that meet most verification requirements, which can be found in default. xml under com. opensymphony. xwork2.validator. validators in the xwork-2.x.jar.

For the prompt after verification failure, if you want to internationalize, you can specify the key attribute for the message. The key value is the key in the resource file.

An example of the validator:

1> email: email address checker

 
  
   
Invalid email address
  
 

2> regex: Regular Expression

 
  
  ^1[358]\d{9}$ 
  
   
Incorrect mobile phone number format!
  
 

3> required

 
  
   
Required Properties
  
 

4> requiredstring: Required string checker

 
 
  
// Remove the leading and trailing Spaces
  True
  
   
Prompt that the string attribute is required
  
 

5> stringlength: String Length checker

 
  10
  3// Remove the leading and trailing Spaces
  True
  产品名称应在2-10个字符之间
  
 

6> int: Certificate validator

 
   
  1  
  150  
  
   
The age must be between 1 and.
  
 

7> Field OGNL expression validator

  
   
      imagefile.length()<=0         
   
    
File cannot be blank
    
  
 

2.Verify the specified Action method:

Others are the same as above. You only need to change the format name of the validation file:

ActionClassName-actionNameMethodName-validation.xml, where

ActionClassName is a simple class name, And actionNameMethodName is the name and

The name of the method to be called in Action.-validation. xml is a fixed method.

Note:When two types of validation rule files are provided for an Action, the system first searches globally and then in a specific order, that is, the system continues to search for a specific validation file when it finds the global validation file, then, all the teaching and research rules are summarized and applied to the Action Method verification. If the two verification files contain the specified validation conflict, use the specific validation file rules.

When an Action inherits an Action, the validation file of the parent acting class is first searched, followed by the validation file of the subclass, and finally summarized and applied to the Action.




















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.