Struts form validation using DynaValidatorForm


Here we explain how to validate a form using DynaValidatorForm in struts. The requirements is very simple we just make a login form with two fields username and password.
So our requirements are:
  • All field should be mandatory. 
  • Minimum length of user name is 6-digits.
  • And minimum length of password no is 5-digits.
See here user interfaces:

First page is user login:


Login without username and password:


After putting the username and password same then:



So our requirements are very clear what we have to develop.Since we are developing in struts so we need some jar files and tld files:

Jar Files:
  • commons-beanutils.jar
  • commons-collections.jar
  • commons-digester.jar
  • commons-fileupload.jar (your choice for uploading file)
  • commons-lang.jar
  • commons-logging.jar
  • commons-validator.jar
  • jakarta-oro.jar
  • struts.jar
  • struts-legacy.jar
Tld files:
  • struts-bean.tld
  • struts-html.tld
  • struts-logic.tld
  • struts-nested.tld
  • struts-template.tld
  • struts-tiles.tld
All these jar and tld files are free available so you can download and copy to all these jar files in your lib and tld in WEB-INF.

Here project name is StrutsApp Now we need following files:
  1. LoginAction.java
  2. Application.properties
  3. login.jsp
  4. home.jsp
  5. web.xml
  6. struts-config.xml
  7. myform-validators.xml
LoginAction.java

package com.javaforecast4u;

import javax.servlet.http.*;

import org.apache.struts.action.*;
import org.apache.struts.validator.DynaValidatorForm;

public class LoginAction extends Action {
public ActionForward execute(ActionMapping am,ActionForm af,HttpServletRequest req, HttpServletResponse res)throws Exception{
    DynaValidatorForm dvf=(DynaValidatorForm)af;
    String un=dvf.get("uname").toString();
    String pw=dvf.get("pword").toString();
    //Call Model
    String str="login";
    if(un.equals(pw)){
         str="success";
         req.setAttribute("UN", un);
    }else{
         ActionErrors errors=new ActionErrors();
         errors.add("invalid",new ActionError("login.invalid"));
         this.saveErrors(req, errors);
    }
    ActionForward forward=am.findForward(str);
    return forward;
}
}

Application.properties



login.invalid=<font color="red" size="5">Incorrect Username or Password</font>
errors.required=<font color="red" size="5">{0} is Required</font>
errors.minlength=<font color="red" size="5">{0} cannt be less than {1} character</font>
errors.maxlength=<font color="red" size="5">{0} cant be Greater than {2} characters</font>
login.username=Username



login.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<body bgcolor="yellow">
<h3>Struts form validation using DynaValidatorForm</h3>
<h2>Login Information</h2>
<html:form action="/login.do">
<html:errors property="invalid"/>
<table align="left">
<tr><td>Username</td>
<td><html:text property="uname"/></td>
<td><html:errors property="uname"/></td>
</tr>
<tr><td>Password</td>
<td><html:password property="pword"/></td>
<td><html:errors property="pword"/></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit value="Login"/></td>
</tr>
</table>
<html:javascript formName="loginForm"/>
</html:form>

</body>
</html>


home.jsp

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html>
<body bgcolor="yellow">
<h3>Struts form validation using DynaValidatorForm</h3>
<h2>Mr. <bean:write name="UN" scope="request"/></h2>
<h2>WelCome To Java Forecast 4u</h2>

</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>SLab5</display-name>
  <welcome-file-list>
   
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>action</servlet-name>
  <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>
  <init-param>
  <param-name>debug</param-name>
  <param-value>3</param-value>
  </init-param>
  <init-param>
  <param-name>detail</param-name>
  <param-value>3</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>
</web-app>


struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

<form-beans>
<form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="uname" type="java.lang.String"/>
<form-property name="pword" type="java.lang.String"/>
</form-bean>
</form-beans>
<global-forwards>
<forward name="login" path="/login.jsp"/>
</global-forwards>

<action-mappings>
<action path="/login" name="loginForm"
        type="com.javaforecast4u.LoginAction"
        scope="session"
        input="/login.jsp">

  <forward name="success" path="/home.jsp"/>
  </action>
       
</action-mappings>
<message-resources parameter ="com.javaforecast4u.ApplicationResources"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/myform-validators.xml"/>
</plug-in>
</struts-config>



myform-validators.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN" "validator_1_0_1.dtd" >
<form-validation>
<formset>
<form name="loginForm">
<field property="uname" depends="required,minlength,maxlength">
<arg0 key="login.username" resource="true"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>6</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>9</var-value>
</var>
</field>
<field property="pword" depends="required,minlength,maxlength">
<arg0 key="Password" resource="false"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>8</var-value></var>
</field>
</form>
</formset>
</form-validation>



I hope you will enjoy..... have a good day!

4 comments :

  1. Lekhraj Prasad4 June 2012 at 23:21

    can u just explain the flow of this programme

    ReplyDelete
  2. Hai, this is harish iam new to struts i have small problem while executing the above program that is when i submit the form without filling the form fields it is not throwing the validation messages where i have went wrong
    please help me in solving this problem,

    Thank you.

    ReplyDelete
  3. Can u plz tel me what is the purpose of resource="false/true'

    ReplyDelete
  4. The purpose of resource is if u are giving resource is true the mentioned key is taking from resourceBundle. if u are specifying false what ever the value given in key the same value is used to display error message.

    ReplyDelete