Strut2 Basic Validation Using ActionSupport
Validation of input is an important part of any Web application. One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons. . All Apache Jakarta frameworks, including Struts, can use a common Jakarta Validation Framework for streamlining this aspect of Web application development. The Validation Framework allows you to define validation rules and then apply these rules on the client-side or the server-side
Strut2 Basic Validation
Struts 2 provides a rich and highly configurable validation framework. ActionSupport provides a quick form of basic validation that will serve well in many cases. ActionSupport implements two interfaces that coordinate with one of the interceptors from the default stack, the DefaultWorkflowInterceptor, to provide basic validation. If your package extends the struts-default package, thereby inheriting the default interceptor stack, and your action extends ActionSupport, thereby inheriting implementation of the two necessary interfaces, then you already have everything you need for clean validation of your data.
In this article we are seeing interceptors which are participate in the validation. Following list shows the declaration of the workflow interceptor which is found in the struts-default.xml file.
Declaration of DefaultWorkflowInterceptor from struts-default.xml
. . .
<interceptor name="workflow"
class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>
. . .
<interceptor-stack name="defaultStack">
. . .
<interceptor-ref name="params"/>
. . .
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
. . .
<interceptor-stack name="defaultStack">
. . .
In the above list we first see the declaration element for workflow interceptors, specifying a name and an implementation class. This is called workflow interceptors because it will divert the workflow of the request back to the input page if a validation error is found. Note that the params interceptor comes before the workflow interceptor. The params interceptor will move the request data onto our action object. Then, the workflow interceptor will help us validate that data before accepting it into our model. The workflow interceptor must fire after the params interceptor has had a chance to move the data on to the action object. As with most interceptors, sequence is important.
Now, let’s see how this basic validation actually works. As with the params interceptor, the workflow interceptor removes the logic of validation from the action’s execution logic. When the workflow interceptor fires, it’ll first look for a validate() method on the action to invoke. We will place your validation logic in validate(). This method is defined in the com.opensymphony.xwork2.Validateable interface. Actually Action-Support implements the validate() method of Validateable interface, but we have to override its empty implementation with our own specific validation logic.
Now let's see a example of Registering a New user to the website. Here we are showing how this basic validation works in this example. See the comments to understand the flow of code.
// 1-->>> Our Action Register extend Action-Support
public class Register extends ActionSupport{
// 2-->>> provide an execute() method that contains the business logic
public String execute(){
User user = new User();
user.setPassword( getPassword() );
user.setPortfolioName( getPortfolioName() );
user.setUsername( getUsername() );
getPortfolioService().createAccount( user );
return SUCCESS;
}
// 3-->>> set of JavaBeans properties used in the program
private String username;
private String password;
private String webSiteServiceName;
public String getWebSiteServiceName () {
return webSiteServiceName;
}
public void setWebSiteServiceName (String webSiteServiceName) {
this. webSiteServiceName = webSiteServiceName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
// 4-->>>Action provides a validate() method that contains all of our logic for checking the validity of the data received by our JavaBeans properties.
public void validate(){
WebSiteService ws = getWebSiteService();
// In the below code we are validating the length of each of String property
if ( getPassword().length() == 0 ){
//data doesn’t validate, we create and store an error via methods provided by the //ActionSupport superclass, such as addFieldError().
addFieldError( "password", getText("password.required"));
}
if ( getUsername().length() == 0 ){
addFieldError( "username",getText("username.required"));
}
if ( getwebSiteServiceName().length() == 0 ){
addFieldError( "webSiteServiceName", getText("websiteName.required" )););
}
if ( ws.userExists(getUsername() ) ){
addFieldError("username", "This user already exists.");
}
}
public WebSiteService getWebSiteService( ) {
return new WebSiteService();
}
In the above example if username or password fields are empty we are calling a method that adds an error message. After all the validation logic executed the control returns to the workflow interceptor. The workflow interceptor will check to see whether any error messages were generated by the validation logic. It does this by calling The com.opensymphony.xwork2.ValidationAware's hasErrors() method to see if there were any problems with validation. If it finds errors, then the workflow interceptor will alter the workflow of the request. It’ll immediately abort the request processing and return the user back to the input form, where the appropriate error messages will be displayed on the form.
The com.opensymphony.xwork2.ValidationAware interface defines methods for storing and retrieving error messages. ActionSupport class implements this interface . ValidationAware interface provides two methods those are:
addFieldError ( String fieldName, String errorMessage ) // to add field errot
addActionError ( String errorMessage )// to add action scoped error.
We have to bundle error messages together into external and maintainable resource bundles, commonly implemented with simple properties files. ActionSupport implements two interfaces that work together to provide this localized message text functionality. The first interface, com.opensymphony.xwork2.TextProvider, provides access to the messages themselves. This interface exposes a flexible set of methods by which you can retrieve a message text from a resource bundle. The getText() method of TextProvider to retrieve our messages from properties files based upon a key..