Wednesday, July 20, 2011

Struts - Step6. Adding validations to your ActionForm

The following example takes you through the process of adding validations to your form object. The validations for DynaActionForm can be seen in the next section.

The complete code snippet can be seen at the end of this page.

AddUserForm.java

@Override
public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();

    // Validate User Id.
    if (userId == null || userId.trim().length() == 0) {
        errors.add("userId", new ActionMessage("errors.userId.invalid"));
    } else if (userId.length() > 10) {
        errors.add("userId", new ActionMessage(
                "errors.userId.length.invalid"));
    }

    // Validate User Name.
    if (name == null || name.trim().length() == 0) {
        errors.add("name", new ActionMessage("errors.name.invalid"));
    } else if (name.equals(userId)) {
        errors.add("name", new ActionMessage("errors.name.value.invalid"));
    }

    return errors;
}

application.properties

helloworldMsg=Hello There. Welcome to my Struts Application

## Used by html.error tag for ordering the errors.
errors.header=<UL> 
errors.footer=</UL> 
errors.prefix=<LI> 
errors.suffix=</LI>

# Error Tags
errors.userId.invalid=Invalid User Id. Please provide a valid one
errors.userId.length.invalid=User Id cannot be more than 10 characters long
errors.name.invalid=Invalid name. Please provide a valid one
errors.name.value.invalid=Name cannot be same as User Id

HelloWorld.jsp

<!-- This tag is used to display all the errors in this page. -->
<html:errors />
<br>
<html:form action="/addUser.do" method="POST">
    <table>
        <tr>
            <td align="right">User Id:</td>
            <td><html:text property="userId" size="15" /></td>
            <td><html:errors property="userId" /></td>
        </tr>
        <tr>
            <td align="right">User Name:</td>
            <td><html:text property="name" size="15" /></td>
            <td><html:errors property="name" /></td>
        </tr>
        <tr>
            <td align="right">Password:</td>
            <td><html:password property="password" size="15" /></td>
        </tr>
        <tr>
            <td></td>
            <td><html:submit>Add User</html:submit></td>
        </tr>
    </table>
</html:form>

struts-config.xml

<action path="/addUser" type="org.mybusiness.strutstutorial.actions.AddUserAction" 
    name="addUserForm" validate="true" input="/helloworld.do">
        <forward name="SUCCESS" path="/WEB-INF/jsp/AddUserSuccess.jsp"></forward>
</action>

Screenshots



Complete Code

AddUserForm.java

package org.mybusiness.strutstutorial.forms;

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 AddUserForm extends ActionForm {

    private static final long serialVersionUID = 1L;

    private String userId;

    private String password;

    private String name;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {

        ActionErrors errors = new ActionErrors();

        // Validate User Id.
        if (userId == null || userId.trim().length() == 0) {
            errors.add("userId", new ActionMessage("errors.userId.invalid"));
        } else if (userId.length() > 10) {
            errors.add("userId", new ActionMessage(
                    "errors.userId.length.invalid"));
        }

        // Validate User Name.
        if (name == null || name.trim().length() == 0) {
            errors.add("name", new ActionMessage("errors.name.invalid"));
        } else if (name.equals(userId)) {
            errors.add("name", new ActionMessage("errors.name.value.invalid"));
        }

        return errors;
    }
}

HelloWorld.jsp

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
    prefix="html"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body bgcolor="#ffe">

<h2>Hello World. Welcome to my Struts based web application</h2>

<h4>The following message is displayed using struts bean:message
tag</h4>
<bean:message key="helloworldMsg" />
<br>
<!-- This tag is used to display all the errors in this page. -->
<html:errors />
<br>
<html:form action="/addUser.do" method="POST">
    <table>
        <tr>
            <td align="right">User Id:</td>
            <td><html:text property="userId" size="15" /></td>
            <td><html:errors property="userId" /></td>
        </tr>
        <tr>
            <td align="right">User Name:</td>
            <td><html:text property="name" size="15" /></td>
            <td><html:errors property="name" /></td>
        </tr>
        <tr>
            <td align="right">Password:</td>
            <td><html:password property="password" size="15" /></td>
        </tr>
        <tr>
            <td></td>
            <td><html:submit>Add User</html:submit></td>
        </tr>
    </table>
</html:form>
</body>
</html>

struts-config.xml

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

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

<struts-config>

    <form-beans>
        <form-bean name="addUserForm"
            type="org.mybusiness.strutstutorial.forms.AddUserForm" />
    </form-beans>

    <!--
        Using Global Forwards to forward to the desired view for Home Page
    -->
    <global-forwards>
        <forward name="HelloWorld" path="/WEB-INF/jsp/HelloWorld.jsp" />
    </global-forwards>

    <!-- Contains the URL Mapping -->
    <action-mappings>
        <action path="/helloworld"
            type="org.mybusiness.strutstutorial.actions.HelloWorldAction" />

        <action path="/addUser"
            type="org.mybusiness.strutstutorial.actions.AddUserAction" name="addUserForm"
            validate="true" input="/helloworld.do">
            <forward name="SUCCESS" path="/WEB-INF/jsp/AddUserSuccess.jsp"></forward>
        </action>
    </action-mappings>

    <message-resources parameter="application" />
</struts-config>

No comments:

Post a Comment