English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Struts2Detailed Tutorial on Data Input Validation

I. Introduction

1.1What is input validation? Why do we need input validation?

In the previous article, we learned about data type conversion. We mentioned two methods for handling data at the representation layer, and also mentioned that user input data needs to be converted to the correct type to get the data we want. So, how do we determine that the data after type conversion is what we want? It's a bit tricky. You can think like this: the age of a grown man is18years old, and now you want to get18This data, but, the user input32After type conversion is correct, but the data is not what you want. What should we do in this case? Therefore, input validation is useful here.

The relationship between type conversion and input validation is that type conversion is the premise of input validation. If type conversion fails, there is no need to perform input validation. However, in many cases, type conversion and input validation are completed simultaneously.

There are two types of input validation:

1Client-side validation;

2Server-side validation. This section mainly explains server-side validation (rewriting the ValidateXxx method and xml configuration file validation).

1.2Rewrite the validation process of the ValidateXxx method.

1The type converter is responsible for converting the request parameters to the correct type and setting these values as properties of the Action.

2During the execution of type conversion, exceptions may occur, if an exception occurs, the exception information will be automatically saved to the ActionContext, and the conversionError interceptor is responsible for encapsulating it into fieldError

3Call the ValidateXxx() method through reflection, where Xxx is the method name corresponding to the handling logic of the user request to be processed

4Call the Validate method of the Action class

5If the above steps do not appear fieldError, the handling method of the user request in the Action will be called, if fieldError appears, the system will transfer to the view specified by the input logic view.

Second, input validation

2.1There are two ways to explain input validation here:

1Rewrite the Validate method or customize the ValidateXxx method (where Xxx is the name defined by yourself, this method will be executed first, followed by the execution of the Validate method)

2Create a new xml for validation

2.2Rewrite the Validate method

In the MVC framework, there will be a standardized data validation part provided, Struts2Here we provide a Validate method, by rewriting the Validate method, we can perform input validation, but there are two points to know when rewriting the Validate method:1Validate method will be executed before the execute method;2Validate method will execute validation rules for all actions, in order to distinguish a certain action, we can use ValidateXxx method.

Note: The following example is an example of using local type conversion and input validation together.

A simple registration verification example:

Create an entity class User:

 User

Create a view: Register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8>
<title>Register User</title>
</head>
<body>
  <h2>Use the validateXXX() method for verification</h2>
  <form action="register_test">
    User: <input type="text" name="user"><br/>
    Password: <input type="password" name="user"><br/>
    Password: <input type="password" name="user"><br/>
    <input type="submit" value="Submit">
  </form> 
</body>
</html>

Create a RegisterAction class that inherits from ActionSupport

package com.validatexxx;
import com.opensymphony.xwork2.ActionSupport;
//Rewrite the validate() and validateXXX specified methods for verification
/*
 * In the struts.xml configuration, the method method is set to test(), and the ValidateTest() method will be called first
 * Then the validate method is called
 * After the test method is called
 * */
public class RegisterAction extends ActionSupport {
  private User user;
  public User getUser() {
    return user;
  }
  public void setUser(User user) {
    this.user = user;
  }
  //2
  @Override 
  public void validate(){   
   System.out.println("Override Validate method");
   if (null == user.getPassword() || "".equals(user.getPassword()) || null == user.getRepassword() || "".equals(user.getRepassword())) { 
       this.addFieldError("repassword", "repassword should be the same as password"); 
      return; 
     } 
   if (!user.getPassword().equals(user.getRepassword())) { 
     //When there is data in FieldError, the server will automatically redirect us to the input logical view
     this.addFieldError("repassword", "repassword should be the same as password"); 
     } 
  }
  //1
  public void validateTest() {
    System.out.println("Custom validation method:ValidateTest");
  }
  //3
  public String test() {
    System.out.println("test:method");
    return SUCCESS;
  }
}

Note: here the attribute is User, so the name of the parameter in your jsp page should be the instance name user, and then you also need to create a type converter that returns a class filled with data

Create a struts.xml and place it in the WEB directory-INF/classes/struts.xml

Note: here the method must be the ValidateXxx() method you define yourself, and the author here is test. Use*in struts2strict must also be configured-method-invocation="false", it is said that this is because the version is too high, its security has increased, and it must be added in order to use it*

Create a Usertypeconverter class that inherits from StrutsTypeConverter (create a type converter)

package com.validatexxx;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
//Type conversion class
public class Usertypeconverter extends StrutsTypeConverter {
  @Override
  public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
    System.out.println("Usertypeconverter: Type conversion!");
    User user = new User();
    user.setUsername(arg1[0]);
    user.setPassword(arg1[1]);
    user.setRepassword(arg1[2]);
    return user;
  }
  @Override
  public String convertToString(Map arg0, Object arg1) {
    User u = (User)arg1;
    return u.getUsername()+"!";
  }
}

Note: After the type converter is created, a new RegisterAction needs to be created-conversion.properties, placed in the same directory

The content of the file is:

The former is the property name in RegisterAction, and the latter is the specific path of the type converter.

 New success view: success.jsp

 success.jsp

New error view: input.jsp

 input.jsp

The effect of successful code execution is as follows:

Register.jsp page 

The successfully redirected page is: success.jsp

Console test results are:

Data jumps to Usertypeconverter for type conversion, then jumps to RegisterAction, executes ValidateTest method(), Validate, test returns SUCCESS, and then executes the view of result.

Let's see the order in which the code execution fails:

Register.jsp page

input.jsp page

Console test effect:

Inside the Validate method, the author's code is: this.addFieldError(), as mentioned before, if an error is added, the server will automatically redirect us to the error interface. It will return input, and input is configured in struts.xml, which will redirect to the input.jsp interface.

2.3New xml for input validation

Create the view interface: Test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8>
<title>Use XML Validation</title>
</head>
<body>
  <s:form action="empinfo" method="post">
   <s:textfield name="name" label="Name" size="20" />
   <s:textfield name="age" label="Age" size="20" />
   <s:submit name="submit" label="Submit" align="center" />
  </s:form> 
</body>
</html>

Create a new Employee class inheriting from ActionSupport

This class uses both overridden Validate methods and XML configuration; we can choose one of them for validation.

package com.validatexxx;
import com.opensymphony.xwork2.ActionSupport;
//The validate() method is used for validation, which is server-side validation!
public class Employee extends ActionSupport {
  private String name;
  private int age;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  //Second, execute this method
  public String execute(){
    System.out.println("execute:")+this.age);
    return SUCCESS;
  }
/*  Use server-side validation: rewrite the validate method();
  //First, execute this method
  //The defect of rewriting the validate method: it will use the validate method to verify every time, causing great waste of resources.
  public void validate(){
    System.out.println("validate");
     if (name == null || name.trim().equals(""))
     {
       //When data is added to this method, the server will return input and then jump to the input.jsp page.
       addFieldError("name","The name is required");
     } 
     if (age < 28 || age > 65)
     {
       addFieldError("age","Age must be in between 28 and 65");
      }
  }
*/
}

Configure in Struts.xml:

Here, success.jsp and input.jsp still use the ones above.

After that, we need to create a new Employee-validation.xml, the path is placed in the same directory as Employee, note that:-validation.xml is fixed and does not change.

The content is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
    "-//Apache Struts//XWork Validator 1.0.3//EN" 
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
 <validators>
  <field name="name">
   <field-validator type="required">
     <message>
      The name is required.
     </message>
   </field-validator>
  </field>
  <field name="age">
   <field-validator type="int">
     <param name="min">29</param>
     <param name="max">64</param>
     <message>
      Age must be between 28 and 65
     </message>
   </field-validator>
  </field>
</validators>

Key point: The dtd restriction of this file must be present, otherwise an error will be returned:

ERROR DefaultDispatcherErrorHandler Exception occurred during processing request: [Connection timed out: connect - [unknown location], null]


Next, we usehttp://localhost:8080/LearStruts2/ValidateJSP/Test.jspaccess.

Test successful:

Test.jsp interface:

success.jsp

Test failed example:

input.jsp interface:

The example given is correct.

In fact, in Struts2There are multiple built-in validators: required validator, required string validator, integer validator, date validator, expression validator, character length validator, regular expression validator, and so on. If needed, the author will explain them one by one.

The following is what the editor introduces to everyone about Struts2Detailed tutorial on data input validation, hoping it will be helpful to everyone. If you have any questions, please leave me a message, and I will reply to everyone in time. I would also like to express my sincere gratitude to everyone for their support of the Naoan tutorial website!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like