Resources

SAS® AppDev Studio 3.0 Developer's Site

Source Code - Struts Declarative Form Validation Example

Application files index.jsp:
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>

<html>
<head>
    <title><bean:message key="label.index.title" /></title>
</head>
<body>

<h3><bean:message key="label.index.title" /></h3>
<p><a href="view.submitcomment.do">
  <bean:message key="label.index.commentSubmissionForm"/></a>

</body>
</html>
submitcomment.jsp:
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>

<html>
<header><title>Comment Submission Form</title></header>
<body>

<h3>Comment Submission Form</h3>
  <ul>
   <font color=red>
    <html:messages id="message">
      <li><bean:write name="message"/></li>
    </html:messages>
   </font>
  </ul>

<p>* Indicates a required field<p>

<table>
 <html:form action="/submitcomment">
  <tr>
   <td>* User name:</td>
   <td><html:text property="userID"></html:text></td>
  </tr>
  <tr>
   <td>* Email:</td>
   <td><html:text property="email"></html:text></td>
  </tr>
  <tr>
    <td colspan="2"><html:checkbox property="shareEmail">
       Let forum viewers see this email address</html:checkbox></td>
  </tr>
  <tr>
   <td>Zip code:</td>
   <td><html:text property="zipCode"></html:text></td>
  </tr>
  <tr valign="top">
   <td>* Comments:</td>
   <td><html:textarea property="comments" cols="40" rows="10"></html:textarea></td>
  </tr>
  <tr>
   <td><html:submit value="Submit"></html:submit></td>
  </tr>
 </html:form>
</table>
</body>
</html>
thankyou.jsp:

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

 <html>
 <head><title>Thank you for your comments</title></head>
 <body>
 <h3>Comment Submission Accepted</h3><p>

 <bean:parameter id="userID" name="userID"/>

 Thank you for your comments, <bean:write name="userID" />.<p>
 <logic:present parameter="shareEmail">
 We will display your email address with your comments on the public forum page.
 </logic:present>
 </body>
 </html>
 
SubmitCommentAction.java:
package app;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.io.*;

public class SubmitCommentAction extends Action
{
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
      throws Exception
   {
      // *** Your business logic would go here ***
      // For example, perhaps to save the form values to a database.
      // For simplicity of illustration, we just print a couple values:
       String userID = req.getParameter("userID");
      String shareEmail = req.getParameter("shareEmail");
      System.out.println("userID = " + userID);
      if (null != shareEmail)
         System.out.println("shareEmail = " + shareEmail);

       return mapping.findForward("success");

      // If your business logic failed, then you would
      // return mapping.findForward("failure");
   }

}
application.properties:
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
# -- validator --
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# -- other --
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.

#-- application-specific messages --
label.index.title=Struts Declarative Validation Demo
label.index.commentSubmissionForm=Comment Submission Form

commentForm.userID=User name entry
commentForm.email=Email entry
commentForm.zipCode=Zip Code entry
commentForm.comments=Comments entry
struts-config.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>

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

<!--
     This is a blank Struts configuration file with an example
     welcome action/page and other commented sample elements.

     Tiles and the Struts Validator are configured using the factory defaults
     and are ready-to-use.

     NOTE: If you have a generator tool to create the corresponding Java classes
     for you, you could include the details in the "form-bean" declarations.
     Otherwise, you would only define the "form-bean" element itself, with the
     corresponding "name" and "type" attributes, as shown here.
-->

<struts-config>

<!-- ==================================== Data Source Configuration -->

<!--
    <data-sources>
        <data-source>
            <set-property
                property="autoCommit"
                value="false"/>
            <set-property
                 property="description"
                 value="Example Data Source Configuration"/>
            <set-property
                property="driverClass"
                value="org.postgresql.Driver"/>
            <set-property
                property="maxCount"
                value="4"/>
            <set-property
                property="minCount"
                value="2"/>
            <set-property
                property="password"
                value="mypassword"/>
            <set-property
                property="url"
                value="jdbc:postgresql://localhost/mydatabase"/>
            <set-property
                property="user"
                value="myusername"/>
        </data-source>
    </data-sources>
-->

<!-- ======================================== Form Bean Definitions -->

    <form-beans>
    <!-- sample form bean descriptor for an ActionForm
        <form-bean
            name="inputForm"
            type="app.InputForm"/>
    end sample -->

    <!-- sample form bean descriptor for a DynaActionForm
         <form-bean
             name="logonForm"
             type="org.apache.struts.action.DynaActionForm">
             <form-property
                 name="username"
                 type="java.lang.String"/>
             <form-property
                 name="password"
                type="java.lang.String"/>
    end sample -->

      <form-bean name="commentForm"   type="org.apache.struts.validator.DynaValidatorForm">
         <form-property name="userID" type="java.lang.String"/>
         <form-property name="email" type="java.lang.String"/>
         <form-property name="shareEmail" type="java.lang.String"/>
         <form-property name="zipCode" type="java.lang.String"/>
         <form-property name="comments" type="java.lang.String"/>
      </form-bean>

   </form-beans>


<!-- ================================= Global Exception Definitions -->

    <global-exceptions>
        <!-- sample exception handler
        <exception
            key="expired.password"
            type="app.ExpiredPasswordException"
            path="/changePassword.htm"/>
        end sample -->
    </global-exceptions>


<!-- =================================== Global Forward Definitions -->

    <global-forwards>
        <!-- Default forward to "Welcome" action -->
        <!-- Demonstrates using index.jsp to forward -->
        <forward
            name="welcome"
            path="/Welcome.do"/>
    </global-forwards>


<!-- =================================== Action Mapping Definitions -->

    <action-mappings>
        <!-- Default "Welcome" action -->
        <!-- Forwards to Welcome.jsp -->
        <action
            path="/Welcome"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/pages/Welcome.htm"/>

    <!-- sample input and input submit actions
        <action
            path="/Input"
            type="org.apache.struts.actions.ForwardAction"
            parameter="/pages/Input.htm"/>
        <action
            path="/InputSubmit"
            type="app.InputAction"
            name="inputForm"
            scope="request"
            validate="true"
            input="/pages/Input.htm"/>
    end samples -->

      <action
         path="/view.submitcomment"
         parameter="/submitcomment.htm"
         type="org.apache.struts.actions.ForwardAction"
         name="commentForm"
         input="/submitcomment.htm"
         validate="false">
      </action>

      <action
         path="/submitcomment"
         type="app.SubmitCommentAction"
         name="commentForm"
         input="/submitcomment.htm"
         validate="true">
            <forward name="success" path="thankyou.htm"  />
            <forward name="failure" path="/submitcomment.htm" />
      </action>


    </action-mappings>


<!-- ===================================== Controller Configuration -->

    <controller
       processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>


<!-- ================================ Message Resources Definitions -->

    <message-resources parameter="resources.application"/>


<!-- ======================================= Plug Ins Configuration -->


  <!-- ========== Tiles plugin ===================  -->
  <!--												-->
  <!--
     This plugin initialize Tiles definition factory. This later can takes some
    parameters explained here after. The plugin first read parameters from web.xml, then
    overload them with parameters defined here. All parameters are optional.
    The plugin should be declared in each struts-config file.
       - definitions-config: (optional)
            Specify configuration file names. There can be several comma
          separated file names (default: ?? )
       - moduleAware: (optional - struts1.1)
            Specify if the Tiles definition factory is module aware. If true (default),
         there will be one factory for each Struts module.
         If false, there will be one common factory for all module. In this later case,
         it is still needed to declare one plugin per module. The factory will be
         initialized with parameters found in the first initialized plugin (generally the
         one associated with the default module).
           true : One factory per module. (default)
           false : one single shared factory for all modules
      - definitions-parser-validate: (optional)
           Specify if xml parser should validate the Tiles configuration file.
           true : validate. DTD should be specified in file header. (default)
           false : no validation

     Paths found in Tiles definitions are relative to the main context.
  -->
    <!-- comment following if struts1.0.x -->
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config"
	                     value="/WEB-INF/tiles-defs.xml" />
        <set-property property="moduleAware" value="true" />
        <set-property property="definitions-parser-validate" value="true" />
    </plug-in>

    <!-- end comment if struts1.0.x -->

    <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>
validation.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">

<form-validation>

<!--
     This is a blank Validator form file with a commented examples.
-->

    <global>

        <!-- An example global constant
        <constant>
            <constant-name>postalCode</constant-name>
            <constant-value>^\d{5}\d*$</constant-value>
        </constant>
        end example-->

      <constant>
         <constant-name>zipmask</constant-name>
         <constant-value>^\d{5}(-\d{4})?$</constant-value>
      </constant>

    </global>

    <formset>

        <!-- An example form
        <form name="logonForm">
            <field
                property="username"
                depends="required">
                    <arg0 key="logonForm.username"/>
             </field>
         <field
            property="password"
            depends="required,mask">
            <arg0 key="logonForm.password"/>
            <var>
                <var-name>mask</var-name>
                <var-value>^[0-9a-zA-Z]*$</var-value>
            </var>
         </field>
        </form>
        end example form -->

      <form name="commentForm">
         <field
            property="userID"
            depends="required,mask">
            <arg0 key="commentForm.userID"/>
            <var>
               <var-name>mask</var-name>
               <var-value>^[0-9a-zA-Z ]*$</var-value>
            </var>
         </field>
         <field
            property="email"
            depends="required,mask">
            <arg0 key="commentForm.email"/>
            <var>
               <var-name>mask</var-name>
               <var-value>^[-A-Za-z0-9_.]+@[-A-Za-z0-9_.]+\.[A-Za-z]{2,}$</var-value>
            </var>
         </field>
         <field
            property="zipCode"
            depends="mask">
            <arg0 key="commentForm.zipCode"/>
            <var>
               <var-name>mask</var-name>
               <var-value>${zipmask}</var-value>
            </var>
         </field>
         <field
            property="comments"
            depends="required">
            <arg0 key="commentForm.comments"/>
         </field>
      </form>

    </formset>

    <!-- An example formset for another locale
    <formset language="fr">

        <constant>
            <constant-name>postalCode</constant-name>
            <constant-value>^[0-9a-zA-Z]*$</constant-value>
        </constant>

   </formset>
   -->

</form-validation>

web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <!-- Standard Action Servlet Configuration (with debugging) -->
    <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>2</param-value>
            </init-param>
        <init-param>
            <param-name>detail</param-name>
            <param-value>2</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>


    <!-- Standard Action Servlet Mapping -->
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>


    <!-- The Usual Welcome File List -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>