1. Preface
1.1. What is input verification? Why do I need to enter verification?
In the previous article, we learned about data type conversion. We mentioned two methods of presentation layer data processing. We also mentioned that the user input data needs to be type conversion to obtain the data we want. So, how do we determine that the data after type conversion is the data we want? It's a bit traverse here. You can think of it like this: an adult man is 18 years old, and you want to get the data of 18 now, but the user inputs 32 and it is also correct to convert it through type, but the data is not what you want. What should we do at this time? So input verification is useful here.
The relationship between type conversion and input verification is: type conversion is the prerequisite for input verification. If both type conversions are wrong, then there is no need to perform input verification. But often type conversion and input verification are done at the same time.
There are two types of input verification:
1. Client verification;
2. Server-side verification. What we mainly explain here is server-side verification (rewrite ValidateXxx method and xml configuration file verification)
1.2. Verification process of rewriting ValidateXxx method
1. The type converter is responsible for type conversion of the request parameters of the string and set these values to the property values of the Action.
2. An exception may occur during the execution of type conversion. If an exception occurs, the exception information will be automatically saved to the ActionContext. The conversionError interceptor is responsible for encapsulating it into a fieldError.
3. Call ValidateXxx() method through reflection, where Xxx is the method name corresponding to the processing logic that will process the user request.
4. Call the Validate method of Action class
5. If the above steps do not show a fieldError, the processing method for processing user requests in the Action will be called. If a fieldError appears, the system will transfer to the view specified in the input logical view.
2. Input verification
2.1. There are two ways to enter verification here:
1. Rewrite the Validate method or customize the ValidateXxx method (where Xxx is the name you define, the method will be executed first, and the Validate method will be executed)
2. Create a new xml for verification
2.2. Rewrite the Validate method
In the MVC framework, a standardized data verification part is provided. Struts2 provides a Validate method here. We can rewrite the Validate method to perform input verification. However, there are two points to know about rewriting the Validate method: 1. The Validate method will be executed before the execute method; 2. The Validate method will execute verification rules for all Actions. In order to distinguish a certain Action, we can use the ValidateXxx method.
Note: The following examples are examples of local type conversion and input validation.
Simple registration verification example:
Create a new entity class User:
User
Create a new 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>Registered user</title></head><body> <h2>Verify using validateXXX() method</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 new RegisterAction class to inherit ActionSupport
package com.validatexxx;import com.opensymphony.xwork2.ActionSupport;//Rewrite validate() and validateXXX specified methods for verification/* * In struts.xml, the method ValidateTest() method will be called first, and then the test method is called after calling validate method* */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("Rewrite Validate method"); if (null == user.getPassword() || "".equals(user.getPassword()) || null == user.getRepassword() || "".equals(user.getRepassword()))) { this.addFieldError("repassword", "repassword should be the same password"); return; } if (!user.getPassword().equals(user.getRepassword())) { //When data exists in FieldError, the server will automatically jump to the logical view of input this.addFieldError("repassword", "repassword should be the same password"); } } //1 public void validateTest(){ System.out.println("custom verification method: ValidateTest"); } //3 public String test(){ System.out.println("test: method"); return SUCCESS; }}Note: The property here is User, so the name of your jsp page parameter must be written as the name of the instance user, and then you also need to create a type converter to return a class filled with the data
Create a new struts.xml and store it in WEB-INF/classes/struts.xml
Note: The method here must be defined by you after your ValudateXxx() method. Here is the test. If you use *, structs2 must also configure strict-method-invocation="false". It is said that because the version is too high, its security has been increased, and all must be added to use *
Create a new Usertypeconverter class to inherit StrutsTypeConverter (create a type converter)
package com.validatexxx;import java.util.Map;import org.apache.struts2.util.StrutsTypeConverter;//Class of type conversion 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 converter of this type is created, you need to create a new RegisterAction-conversion.properties and place it in the same directory.
The contents of this file are:
The first is the property name you are in RegisterAction, followed by the specific path to the type converter.
Create a new success view: success.jsp
success.jsp
Create a new error view: input.jsp
input.jsp
The effect of successful code execution is as follows:
Register.jsp page
The page that successfully jumped is: success.jsp
The console test results are:
The data jumps to Usertypeconverter for type conversion, then jumps to RegisterAction, execute ValidateTest method(), Validate, and then return SUCCESS, and then execute the result view.
Let's look at the order in which the code fails:
Register.jsp page
input.jsp page
Console test effect:
In the Validate method, the author's code is: this.addFieldError(). As mentioned earlier, if an error is added, the server will automatically help us jump to the wrong interface. It will return input, and the input is configured in struts.xml and will return to the input.jsp interface.
2.3. Create new xml for input verification
Create a new 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 verification</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 to inherit ActionSupport
This class uses the override Validate method and Xml configuration, we can choose one of them for verification
package com.validatexxx;import com.opensymphony.xwork2.ActionSupport;// Use validate() method to verify, this is server-side verification! 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; } //The second step executes this method public String execute(){ System.out.println("execute:"+this.age); return SUCCESS; }/* Verification using the server side: rewrite the validate method(); //The first step is to execute the method //Rewrite the validate method has a flaw: every time you use the validate method to verify, causing great waste of resources. public void validate(){ System.out.println("validate"); if (name == null || name.trim().equals("")) { //When adding data 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:
The success.jsp and input.jsp here still use the above.
After that, we need to create a new Employee-validation.xml and place the path in the same directory as Employee. Note: -validation.xml is fixed and unchanged.
Contents are:
<?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 in between 28 and 65 </message> </field-validator> </field></validators>
Key point: The dtd limit of this file must be, otherwise the return error:
ERROR DefaultDispatcherErrorHandler Exception occurred during processing request: [Connection timed out: connect - [unknown location], null]
Next we use http://localhost:8080/LearStruts2/ValidateJSP/Test.jsp for access.
Tested successfully:
Test.jsp interface:
success.jsp
Test failure example:
input.jsp interface:
The illustration example is correct.
In fact, there are multiple built-in validators in Struts2: required validator, required string validator, integer validator, date validator, expression validator, character length validator, regular expression validator, etc. If necessary, the author will explain this one by one.
The above is a detailed explanation of the Struts2 data input verification tutorial introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!