Wednesday, January 12, 2011

Struts Validation configuration: Struts-config.xml and Validation

Struts Validation configuration: Struts-config.xml and Validation

Here I have written complete Struts-config.xml and Validation related configuration.

=========================Struts-config.xml=====================================
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE struts-config PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
    "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
    <data-sources />
    <!--  All Form Beans Declaration -->
    <form-beans>
        <form-bean name="loginForm" type="com.dmodi.admin.login.form.LoginForm"></form-bean>
        <form-bean name="forgotPasswordForm" type="com.dmodi.admin.login.form.ForgotPasswordForm"/>
    </form-beans>

    <global-exceptions></global-exceptions>

    <global-forwards>
        <forward name="InternalError" path="/jsp/internalError.jsp" />
        <forward name="CustomerSearchAction" path="/CustomerSearch.do" redirect="true" />
    </global-forwards>

    <!--  All Action Declarations. -->
    <action-mappings>
        <action path="/Error" forward="/jsp/error.jsp" name="ErrorPage"/>
        
        <action path="/Login" name="loginForm" type="com.dmodi.admin.login.action.LoginAction" 
                              input="LoginPage" validate="true" scope="request">
            <forward name="LoginPage" path="/jsp/login/login.jsp"/>
            <forward name="CustomerSearchPage" path="/CustomerSearch.do" redirect="true"/>      
            <forward name="ResetPasswordPage" path="/ResetPassword.do" redirect="true"/>
            <forward name="CustomerFileUploadPage" path="/customerFileUpload.do" redirect="true" />
        </action>    

        <action path="/ResetPassword" name="resetPasswordForm" 
                type="com.dmodi.admin.login.action.ResetPasswordAction" validate="true" input="ResetPasswordPage">
            <forward name="ResetPasswordPage" path="/jsp/login/resetPassword.jsp"/>
            <forward name="LoginPage" path="/jsp/login/login.jsp"/>
        </action>
    </action-mappings>

    <controller  processorClass="com.dmodi.admin.DModiWebRequestProcessor" />

    <message-resources parameter="com.dmodi.admin.resource.path.ApplicationResources" />
    <message-resources key="fiResources" parameter="com.dmodi.admin.resource.path.ApplicationResources" />

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

    <plug-in className="org.apache.struts.tiles.TilesPlugin">
        <!-- Path to XML definition file -->
        <set-property property="definitions-config" value="/WEB-INF/tiles-def.xml" />

        <!-- Set Module-awareness to true -->
        <set-property property="moduleAware" value="true" />
    </plug-in>
</struts-config>

==================================================================
//Sample tiles-def.xml
<!DOCTYPE tiles-definitions PUBLIC
    "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
    "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">

<tiles-definitions>
    <definition name="default" path="/layout/defaultAdminTemplate.jsp">
        <put name="header" value="/layout/header.jsp" />
        <put name="menu" value="/layout/menu.jsp" />
        <put name="footer" value="/layout/templateFooter.jsp" />
    </definition>

    <definition name="new" path="/layout/newAdminTemplate.jsp">
        <put name="header" value="/layout/newheader.jsp" />
        <put name="menu" value="/layout/newmenu.jsp" />
        <put name="footer" value="/layout/newtemplateFooter.jsp" />
    </definition>

    <definition name="NewCustomerSearchPage" extends="new">
        <put name="body" value="/jsp/newsearchCustomer.jsp" />
    </definition>

    <definition name="CustomerSearchPage" extends="default">
        <put name="body" value="/jsp/searchCustomer.jsp" />
    </definition>

    <definition name="ExceptionDetailsPage" extends="default">
        <put name="body" value="/jsp/exceptionDetails.jsp" />
    </definition>
</tiles-definitions>
================================OurValidatator.java==============================
//OurValidatator.java (see use of this class in validator-rules.xml below)
package com.dmodi.utility;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.Var;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.FieldChecks;
import org.apache.struts.validator.Resources;

public class OurValidatator extends FieldChecks implements Serializable {
    public static final String CLASS_NAME = OurValidatator.class.getName();
    
    public static boolean validateTwoFieldsAreNotSame(Object bean, ValidatorAction va, Field field, 
            ActionMessages errors, Validator validator, HttpServletRequest request) {

        String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        String sProperty2 = field.getVarValue("secondProperty");
        String value2 = ValidatorUtils.getValueAsString(bean, sProperty2);
        LogHelper.logMessage("In OurValidatator for values: " + value+ " and secondProperty: " + value2);

        if (!GenericValidator.isBlankOrNull(value)) {
            try {
                if (value.equals(value2)) {
                    errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
                return false;
                }
            } catch (Exception e) {
                return true;
            }
        }
    return true;
    }
}
==============================ApplicationResources.properties==============================
//ApplicationResources.properties
errors.header=Please correct the following error(s):
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.twofieldsAreNotSame ={0} and {1} cannot be the same

=============================validator-rules.xml=====================================
//validator-rules.xml
<form-validation>
    <global>
        //User defined validation:    
        <validator  name="twofieldsAreNotSame" 
                    classname="com.dmodi.utility.OurValidatator"
                    method="validateTwoFieldsAreNotSame" 
                    methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction,
                                org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages,
                                org.apache.commons.validator.Validator, javax.servlet.http.HttpServletRequest"
                    depends="" msg="errors.twofieldsAreNotSame" />
        //User defined validation:    
        <validator name="validatePinCode"
                    classname="com.ewp.fiadmin.utility.EwpValidator"
                    method="validatePinCode"
                    methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction,
                                org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages,
                                org.apache.commons.validator.Validator, javax.servlet.http.HttpServletRequest"
                    depends="" msg="errors.pinCodeNotValid" />

        //Existing validation: Struts provide this            
        <validator  name="minlength"
                    classname="org.apache.struts.validator.FieldChecks"
                    method="validateMinLength"
                    methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction,
                                  org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages,
                                  org.apache.commons.validator.Validator, javax.servlet.http.HttpServletRequest"
                    depends="" msg="errors.minlength"
                    jsFunction="org.apache.commons.validator.javascript.validateMinLength" />

    </global>
</form-validation>

=============================validation.xml=====================================
//validation.xml: These validations are called from Form-Bean's validate method.
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">


<form-validation>
    <global>
        <constant>
            <constant-name>phone</constant-name>
            <constant-value> ^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$ </constant-value>
        </constant>
        <constant>
            <constant-name>zip</constant-name>
            <constant-value>^\d{5}\d*$</constant-value>
        </constant>
    </global>

    <formset>
        <form name="loginForm">
            <field property="userName" depends="required">
                <arg0 key="loginForm.userName" />
            </field>
            <field property="password" depends="required">
                <arg0 key="loginForm.password" />
            </field>
            <field property="partnerId" depends="required">
                <arg0 key="loginForm.partnerId" />
            </field>
        </form>
        
        //Here you have to write the method name defined in validator-rules.xml in parameter "depends"
        <form name="updateCustomerForm">
            <field property="pinCode" depends="integer,minlength,maxlength,validatePinCode,twofieldsAreNotSame">
                <arg0 key="NPcustomerCreation.label.PinCode" />
                <arg1 name="minlength" key="${var:minlength}" resource="false" />
                <arg1 name="maxlength" key="${var:maxlength}" resource="false" />
                <var>
                    <var-name>secondProperty</var-name>
                    <var-value>product</var-value>
                </var>    
                <var>
                    <var-name>minlength</var-name>
                    <var-value>6</var-value>
                </var>
                <var>
                    <var-name>maxlength</var-name>
                    <var-value>6</var-value>
                </var>
            </field>
        </form>    

        <form name="forgotPasswordForm">
            <field property="userName" depends="required,minlength,i18nmask">
                <msg name="i18nmask" key="errors.maskUserName" />
                <arg0 key="forgotPasswordForm.userName" />
                <arg1 name="minlength" key="${var:minlength}" resource="false" />
                <var>
                    <var-name>minlength</var-name>
                    <var-value>7</var-value>
                </var>

                <var>
                    <var-name>maskKey</var-name>
                    <var-value>alphaNumericOnly_key</var-value>  //This key comes from ApplicationResource.properties 
                </var>
            </field>
            <field property="email" depends="required,email">
                <arg0 key="forgotPasswordForm.email" />
            </field>
        </form>
    </formset>
</form-validation>
==================================================================

No comments:

Post a Comment