Struts Custom Validation using validate method

In this article we will see how to do custom validation using validate method in Struts.

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-core</artifactId>
      <version>1.3.10</version>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-taglib</artifactId>
      <version>1.3.10</version>
    </dependency>
  
</dependencies>

Do not forget to include maven dependencies in Eclipse IDE as shown in following link.

1. Action Form

Create a Action Form class and name it Login.java that contains the following code.

Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file.

package com.kruders.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 LoginForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    private String userName;
    private String password;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
     
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (userName == null || userName.length() < 1) {
            errors.add("userName", new ActionMessage("error.userName.required"));
        }
        if (password == null || password.length() < 1) {
            errors.add("password", new ActionMessage("error.password.required"));
        }
        return errors;
    }
}

validate() is called before the action class is executed. You can validate your properties and add error messages to this collection for each wrong validation. The return-value of the method is a collection (ActionErrors) of error messages (ActionMessage).

2. Action Class (Controller)

Let us create an Action class that will handle the request.

LoginAction.java

package com.kruders.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
 
import com.kruders.form.LoginForm;
 
public class LoginAction extends Action{
    public ActionForward execute(ActionMapping mapping,ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            LoginForm loginForm = (LoginForm) form;
            if(loginForm.getUserName().equals("test") && loginForm.getPassword().equals("test")){
                return mapping.findForward("success");
            } else {
                return mapping.findForward("fail");
            }
    }
}

3. Properties File

Create ApplicationResources.properties and write the following text.

errors.header=<div style="color:red">
error.userName.required= User Name is required
error.password.required= Password is required

<errors.header=<div style=”color:red”> will highlight error message in red color.

4. View

Create following JSP files, login.jsp, success.jsp and fail.jsp with the following content in your WebContent folder.

login.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<title>Struts Custom Validation - Login Page</title>
</head>
<body>
    
    <html:form action="/login" >
        <table>
            <tr>
                <td>
                    User Name :
                </td>
                <td>
                    <html:text name="LoginForm" property="userName"/>
                </td>
                <td>
                    <html:errors property="userName" />
                </td>
            </tr>
            <tr>
                <td>
                    Password  :
                </td>
                <td>
                     <html:password name="LoginForm" property="password" />
                </td>
                <td>
                        <html:errors property="password" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                   <html:submit value="Login" />
                </td>
                <td></td>
            </tr>
        </table>  
    </html:form>
     
</body>
</html>

The view login.jsp is to provide user to enter login details and submitting for Login. <html:errors property=”userName” /> and <html:errors property=”password” /> tags are used to display the error messages to the user.

success.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<!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>Success Page</title>
    </head>
    <body>
        Login Success. Welcome <bean:write name="LoginForm" property="userName"></bean:write>
    </body>
</html>


The view success.jsp is to show success message.

fail.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Failure Page</title>
    </head>
    <body>
            Invalid User Name or Password 
    </body>
</html>

The view fail.jsp is to show failure message.

5. Struts Config

Create a struts-config.xml file in WEB-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
 "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
  
    <form-beans>
        <form-bean name="LoginForm" type="com.kruders.form.LoginForm"/>
    </form-beans>
 
     
    <global-forwards>
        <forward name="login" path="/login.do"/>
    </global-forwards>
     
    <action-mappings>
        <action input="/login.jsp" name="LoginForm" path="/login"  validate="true" scope="request" type="com.kruders.action.LoginAction">
            <forward name="success" path="/success.jsp" />
            <forward name="fail" path="/fail.jsp" />
        </action>
    </action-mappings>
 
    <message-resources parameter="ApplicationResources" />
     
</struts-config>

6. Deployment Descriptor

Now configure the deployment descriptor. Here, we have asked the container to give our ActionServlet any request that matches the pattern *.do

Add the following configuration information in the web.xml file

<welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
</welcome-file-list>
 
<servlet>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
  
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

7. Run Project

Now when you run the project, following screen will be displayed as shown in Figure 43.1

Figure 43.1 Figure 43.1


When you click Submit button with User Name and Password field empty, following screen will be displayed as shown in Figure 43.2

Figure 43.2 Figure 43.2

The folder structure of the example is shown below in Figure 43.3

Figure 43.3 Figure 43.3

You can download the source code of this example here.

One Response to Struts Custom Validation using validate method

  1. jagan September 23, 2013 at 9:01 am #

    very nice example.

Leave a Reply