The easiest way to validate data in Struts2 is to use validate. We can see from the source code of the Actionsupport class that the Actionsupport class implements a validateable interface. This interface has only one validate method. If the action class implements this interface, Struts2 calls this method first before invoking the Execute method, which we can verify in the Validate method and, if an error occurs, whether the field-level error or the action-level error can be selected based on the error levels. And you can use Addfielderror or addactionerror to add the appropriate error message, if there is an action or field error, STRUTS2 will return "input" (this is not written by developers, automatically returned by Struts2), if the return of the "Input", STRUTS2 will no longer invoke the Execute method. If no error message exists, STRUTS2 calls the Execute method at the end.
These two add methods are similar to the Add method in the Actionerrors class, except that the error message for the Add method requires a Actionmessage object, which is more cumbersome. In addition to adding error messages, you can use the Addactionmessage method to add information after a successful submission. This information can be displayed when the commit is successful.
The above three add methods are defined in the Validationaware interface and have a default implementation in the Actionsupport class. In fact, the implementation in the Actionsupport class actually calls the corresponding method in Validationawaresupport, which is that the three add methods are implemented in the Validationawaresupport class, and the code is as follows:
Private final Validationawaresupport Validationaware = new Validationawaresupport ();
public void Addactionerror (String anerrormessage)
{ validationaware.addactionerror (anerrormessage);
}
public void Addactionmessage (String amessage)
{
validationaware.addactionmessage (amessage);
}
public void Addfielderror (string fieldName, String errormessage)
{
Validationaware.addfielderror ( FieldName, errormessage);
Let's implement a simple validation program to experience the use of a validate method.
First, create a master page (validate.jsp) in the Web root directory, with the following code:
<%@ page language= "java" import= "java.util.*" pageencoding= "GBK"%> <%@ taglib prefix=
"s" uri= "/ Struts-tags "%>