Struts Client Side Validation

In this article we will see client side validation in Struts. validator-rules.xml declares the validation routines and logical names are provided for the validations. If the validation fails when it run, the message(i.e. in ApplicationResources.properties) corresponding to the key specified by the msg attribute will be returned.

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. Create DynaActionForm

First we create an entry for DynaActionForm in struts-config.xml

LoginForm.java

<form-beans>
    <form-bean name="LoginForm"  
        type="org.apache.struts.action.DynaActionForm">
         <form-property name="userName" type="java.lang.String"/>
         <form-property name="password" type="java.lang.String"/>
    </form-bean>
</form-beans>

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 org.apache.struts.validator.DynaValidatorForm;
 
public class LoginAction extends Action{
    public ActionForward execute(ActionMapping mapping,ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
                throws Exception {
             
            DynaValidatorForm loginForm = (DynaValidatorForm) form;
            if(loginForm.get("userName").equals("test") && loginForm.get("password").equals("test")){
                return mapping.findForward("success");
            } else {
                return mapping.findForward("fail");
            }
    }
}

3. Properties File

Create ApplicationResources.properties and write the following text.

errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
 
LoginForm.userName=Name
LoginForm.password=Password

4. Enable Validator Plug-in

Write the following code in struts-config.xml to enable the Validator Plug-in.

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property
        property="pathnames"
        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

5. Validation Rules

The following validations are defined in the validation.xml file.

<form name="LoginForm">
    <field property="userName" depends="required">
        <arg key="LoginForm.userName" />
    </field>
    <field property="password" depends="required,minlength">
        <arg0 key="LoginForm.password" />
        <arg1 key="${var:minlength}" name="minlength" resource="false" />
        <var>
            <var-name>minlength</var-name>
            <var-value>6</var-value>
        </var>
    </field>
</form>

6. 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 Client Side Validation - Login Page</title>
</head>
<body>
    
    <html:form action="/login" onsubmit="return validateLoginForm(this);">
        <table>
            <tr>
                <td>
                    User Name :
                </td>
                <td>
                    <html:text name="LoginForm" property="userName"/>
                </td>
            </tr>
            <tr>
                <td>
                    Password  :
                </td>
                <td>
                     <html:password name="LoginForm" property="password" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                   <html:submit value="Login" />
                </td>
            </tr>
        </table> 
    <html:javascript formName="LoginForm"/>
    </html:form>
     
</body>
</html>

The view login.jsp is to provide user to enter login details and submitting for Login. <html:javascript formName=”LoginForm”/> is used to enable client-side validation in JSP. The formName property of the javascript tag hold the name of the form specified in the validation.xml file. onsubmit is used to specify the javascript code that should be executed when the form is submitted.

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"%>
<!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.

7. 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="org.apache.struts.validator.DynaValidatorForm">
            <form-property name="userName" type="java.lang.String" />
            <form-property name="password" type="java.lang.String" />
        </form-bean>
    </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" />
     
    <!--  Validator plugin -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
     
</struts-config>

8. 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>

9. Run Project

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

Figure 41.1 Figure 41.1


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

Figure 41.2 Figure 41.2

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

Figure 41.3 Figure 41.3

You can download the source code of this example here.

No comments yet.

Leave a Reply