Simple Form Validation with Struts 1 Example

The most important thing in web development is to gather user’s data using forms and processing that data for user’s requirements.  But before processing data collected from the user form we must ensure that the data is correct according to our need. For this type of situation you validate the form data before processing. Today, we will explore struts core classes with an example that supports for the form validation.

Suppose, we have following form in our application to get address of a user:

Address Input Form

Address Input Form

As per our application requirement Name, City and Pin are the mandatory fields. Validation must be carried out to the form data while it is submitted by user and if any of the validation fails, we have to inform the user for.

Struts 1 support this type of validation to be implemented in form bean. ActionForm class contains a method named “validate” which provides validation rules to be applied. If we want to add validation to our form, we have to overwrite this method in our form bean and put the validation logic. We will go through detail implementation steps in this post.

For the fulfillment of the requirement, we have to do following steps:

  1. First of all, we will create a form bean (AddressForm.java) which will overwrite validate method to apply validation rules in the specified field.
  2. Then, we will create jsp page for the HTML form (AddressInput.jsp) which will take input from the user. This jsp page will also contain some new struts 1 taglibs for showing errors in validation process.
  3. Next, we will implement a jsp page (ShowAddress.jsp) to show the address provided by the user.  This page will show to the user only if no validation error present in the form data.
  4. Create a controller helper class (AddressAction.java) which will show the address provided by user in ShowAddress.jsp if no validation error exist otherwise show the address input form again with the error descriptions.
  5. We will learn a new method of storing string values in properties file and show in the jsp page at run time. This facility is provided by struts1 by the use of “message-resources” configuration in struts-config.xml. We will use “MessageResources.properties” file to store validation error description and show them on AddressInput.jsp when a validation error will occur.
  6. And finally, we will configure our struts 1 components in struts-config.xml configuration file.

AddressForm.java

In AddressForm.java, we can see the validate method which do apply the validation rules to the data. Here is the code in AddressForm.java:


package com.raistudies.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class AddressForm extends ActionForm {

    private static final long serialVersionUID = 7760412395861134002L;
    private String name = null;
    private String street = null;
    private String city = null;
    private String country = null;
    private int pin;
    /**
       Getter and Setters of the fields are omitted to make the code short.
    **/

    @Override
    public ActionErrors validate(ActionMapping mapping,
     HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if(this.name == null || this.name.trim().equals(""))
            errors.add("name", new ActionMessage("errors.required","Name"));
        if(this.city == null || this.city.trim().equals(""))
            errors.add("city", new ActionMessage("errors.required","City"));
        if(this.pin == 0)
            errors.add("pin", new ActionMessage("errors.required","Pin"));
        return errors;
    }

    @Override
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.name = null;
        this.street = null;
        this.city = null;
        this.country = null;
        super.reset(mapping, request);
    }

}

The new thing here is the validate method which returns object of type ActionErrors, which internally maintain a list of error description.

errors.add(“name”, new ActionMessage(“errors.required”,“Name”));  : this line is adding a new error description in ActionErrors. The first parameter “name” indicated that the error is related to the form field “name” and the second field is a new instance of ActionMessage which contains the information about the error message to be shown in AddressInput.jsp file. “errors.required” is the key of the text to be displayed which is stored in the MessageResources.properties and “Name” is the format parameter as do work with Java Text Formatter API.

AddressInput.jsp

Following are the content of AddressInput.jsp :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Provide Address Information</title>
</head>
<body>
        Provide address information bellow form :<br/>
        * marked fields are required
        <html:form action="/varifyAddress">
                <div>
                        <html:errors/>
                </div>
                <br/>
                Name : <html:text property="name"/>*<br/><br/>
                Street : <html:text property="street"/><br/><br/>
                City : <html:text property="city"/>*<br/><br/>
                Country : <html:text property="country"/><br/><br/>
                Pin : <html:text property="pin" maxlength="6"/>*<br/><br/>
                <html:submit value="Submit"/>
        </html:form>
</body>
</html>

<html:errors/> tag is used for showing all the errors associate at the time of rendering of the jsp. This will help us to show the validation that will occur with the form data.

AddressAction.java

The execute method of AddressAction class will only check if no error present in data then it will show the ShowAddress.jsp to the user and if error exist then AddressInput.jsp with error description will be shown to user. Here is the execute method of AddressAction class :


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
    if(getErrors(request) == null ||getErrors(request).size() == 0)
        return mapping.findForward("success");
    else
        return mapping.getInputForward();
}

getErrors : This method returns ActionErrors instance that was return in the validate method of form bean.

mapping.getInputForward(): This method returns the ActionForward object associated with the input jsp that is AddressInput.jsp.

MessageResources.properties

Following is the content of MessageResources.properties :

errors.header=<ul>
errors.prefix=<li style="color: red;">
errors.suffix=</li>
errors.footer=</ul>

errors.required = {0} can not be blank.

errors.header, errors.prefix, errors.suffix and errors.footer are build in keys for <html:errors/> in struts 1 to format the view of errors in UI. errors.required is defined by us to show error message. {0} indicate the replacement of first format parameter specified in ActionMessage instance. For example

  1. ActionMessage("errors.required","Name") is the ActionMessage instance.
  2. In property file the value :

errors.required = {0} cannot be blank.

The output of this message will be:

Name cannot be blank.

struts-config.xml

Let’s see the configuration done in struts-config.xml:

<struts-config>
    <!-- ========== Form Bean Definitions ================================== -->
    <form-beans>
        <form-bean name="addressForm" type="com.raistudies.form.AddressForm"/>
    </form-beans>
    <!-- ========== Action Mapping Definitions ============================= -->
    <action-mappings>
            <action name="addressForm" path="/varifyAddress" type="com.raistudies.action.AddressAction"
             scope="session" input="/AddressInput.jsp" validate="true">
                <forward name="success" path="/ShowAddress.jsp" redirect="true"/>
            </action>
    </action-mappings>
    <message-resources parameter="MessageResources"/>
</struts-config>

Here are two new attribute configurations with our action class:

  1.  input=“/AddressInput.jsp”: When using validation in struts “input” attribute in action should be specified if we want to show errors in same form page.
  2. validate=“true”: This attribute says struts that validate method is to be call on form bean.

Now if we run the program in Tomcat 6 the following screen will come to you :

Address Form

Address Form

And after filling the form as above when you will click on “Submit” button following screen will open that will show you the address entered by you :

Address Conformtion

Address Conformtion

If we do not enter “city” and “pin” then click on “Submit” button following ui will indicate the errors :

Validation Error Form

Validation Error Form

That is all from this topic…… HAPPY CODING !
You can download code of the example from following links :
Code : Download
War : Download

Related Posts:

Leave a comment ?

5 Comments.

  1. I savour, result in I found just what I used to be having a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  2. hi it work fine…but i wanna xml based validation like validator frame work…plz help me…bcoz i am begineer…

  3. 😛
    Superb code….
    easy to understand..
    thanks….

  4. Dang! this forum blows…

  5. How to restrict user to enter digits only in pin n not string data

Leave a Comment Cancel reply

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>