Resources

SAS® AppDev Studio 3.0 Developer's Site

How to Build - Struts Declarative Validation Example

Use the detailed instructions below to incrementally build and test this project, or see Quick-Build Instructions to just copy and paste files to create the completed project.

Creating and Testing the index.jsp File

Follow these steps to create and test the index page:

  1. Start a new project by choosing File New.
    1. Select a project type of Web Application Project and enter a project name of StrutsValidation. Click OK.
    2. In Step 1 of the wizard, click Next to accept the default location.
    3. Select Struts Framework Web Application as the template and click Next.
    4. Deselect SAS Taglib & T-beans (which automatically unchecks SAS runtime classes, so that only Struts Tag Library remains checked), and click Next.
    5. Accept the default initial content type of Java Server Page and file name index.jsp by clicking Next.
    6. Select Tag Library JavaServer Page as the template and click Next.
    7. Accept the default Web application project options by clicking Next.
    8. Click Finish to construct and display the initial files for the project.

  2. Create the text strings (which can be internationalized) that will be displayed on the index.jsp page. These key/value pairs go in the application.properties file, which is automatically generated by webAF but not included in the project. To do this:
    • Select Insert File into project, navigate to ...Projects\StrutsValidation\webapp\WEB-INF\Classes\Resources, and choose file application.properties.
    • Add these lines at the end:
      #-- application-specific messages --
      label.index.title=Struts Declarative Validation Demo
      label.index.commentSubmissionForm=Comment Submission Form
      
  3. Now switch the editor back to file index.jsp. Drag and drop a message tag from the bean tab of the Struts palette onto the end of the source code.

    Note: webAF 3.0 displays all tags in the Struts palette as "?" icons. Hover the mouse over each icon to see the Tool Tip that identifies the tag.

  4. Complete the line that will display the title of the page, so it looks like this:
    <h3><bean:message key="label.index.title" /></h3>
    
  5. Finally, complete the page by adding the HTML code and a link to a JSP that will present the comment submission form. We will not refer to that JSP file directly, but will instead link to a Struts action, view.submitcomment.do. This action and the associated JSP will be defined later. The completed page should look like this:
    <%@ 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>
    
  6. If you want to, you can test the initial JSP now:
    1. Select Build Project.
    2. Select Tools Services Start Java Web Server.
    3. Click the Execute in browser button on the toolbar.
    4. When the page appears, don't click on the link yet, because we haven't defined it. Close the browser.

Building the Comment Submission Form

Note: For simplicity, we will not internationalize the content of the login form page, but the principle is simple: just replace any text with <bean:message> tags, referencing the key in the application.properties file.

Follow these steps:

  1. Create a new JSP file:
    1. Choose File [arrow] New.
    2. Select Java Server Page and name it submitcomment.jsp.
    3. Accept the defaults and click Next, and then click Finish.

  2. Select the Html tab of the palette, drag and drop form elements and complete the basic form so it looks like this (after the taglib declarations at the top):

    <html>
    <header><title>Comment Submission Form</title></header>
    <body>
    
    <h3>Comment Submission Form</h3>
    
    <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>
    

Adding Struts Form and Action Definitions and Resting the Form Page

Follow these steps:

  1. Open the struts-config.xml file for editing. Just before the </form-beans> tag, insert the following lines to define the form's request parameters, which can be referenced for validation:
    <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>
    
  2. Just before the </action-mappings> tag, insert the following two actions:
    <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>
    

    The first action tag tells Struts that when the user clicks the link to the /view.submitcomment URL in index.jsp, Struts should forward the request to the submitcomment.jsp page.

    The second action tells Struts that when the user clicks the form's Submit button (in submitcomment.jsp), Struts should validate the results (using declarative validation for the form that you will define shortly). The input attribute indicates the destination if validation fails. In the example, if validation fails, it will be forwarded back to submitcomment.jsp again, to give the user a chance to correct errors and try again. Shortly you will modify submitcomment.jsp so it will display error messages describing problems found during validation.

    If the form content validates successfully, Struts will call an Action class object to handle the business logic, called app.SubmitCommentAction, which we will write later. This class, in turn, will return either "success" or "failure" to indicate where Struts should forward to. In the example, it will normally go to thankyou.jsp (which you will also add shortly), or if something goes awry, back to submitcomment.jsp again.

  3. Test what you have so far by rebuilding the project and clicking the Execute in Browser button. Then click on the Comment Submission Form link to display the form. Don't click on the Submit button in the form, because we haven't defined the validation rules yet.

Defining the Declarative Validation Rules

Follow these steps:

  1. Use the Insert File Into Project command to add the existing file ...Projects\StrutsValidation\webapp\WEB-INF\validation.xml to the project.

  2. In validation.xml, just before the first </formset> tag, insert the following lines to declare the validation you want performed on the 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>
    

    These declarations define which fields are required, and define regular expressions to validate the value of the field properties you previously defined. The zipCode field declaration includes a reference to a ${zipmask} regular expression mask that you will also need to define.

  3. To define zipmask as a global constant available to any form, insert the following lines just before the </global> tag, near the top of validation.xml:
    <constant>
     <constant-name>zipmask</constant-name>
     <constant-value>^\d{5}(-\d{4})?$</constant-value>
    </constant>
    

    Note: This regular expression accepts only US zip codes (either 5 digit or zip+4 format), so in a "real" internationalized application, you would want to provide alternatives or make this field optional.

Creating the Action Class for Business Logic

Follow these steps:

  1. Use the File New command to create a Java source file named SubmitCommentAction.java, with a package name of app. On the second page of the wizard, select Simple Java File.

  2. Edit SubmitCommentAction.java so it extends org.apache.struts.action.Action, and implements the required execute() method. Your completed source file should look like this:
    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");
       }
    }
    

Creating the thankyou.jsp File and Testing the Action Forwarding

Follow these steps:

  1. Create another new Java Server Page file named thankyou.jsp, as a Tag Library Java Server Page.

  2. Edit thankyou.jsp file so that it looks like this:
    <%@ 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>
    

    This page uses Struts bean tags to display the userID value from the form, and a Struts logic tag to conditionally display text depending on whether or not the shareEmail field value was entered in the form.

  3. Optionally, test the Web application again by rebuilding the project and clicking the

    Execute in Browser

    button.

    When you fill out the form, be sure to put in "legitimate" values before you click the Submit button. If all goes well, you should see the thankyou.jsp page displayed.

    If the form validation fails, nothing will appear to happen, because the form page will be re-displayed with its values but no error messages. You need to alter the submitcomment.jsp file so that it can display the errors discovered during validation.

Displaying Validation Errors and Performing Final Testing

Follow these steps:

  1. Add the following lines to submitcomment.jsp, right after the line with <h3>Comment Submission Form</h3>
      <ul>
       <font color=red>
        <html:messages id="message">
          <li><bean:write name="message"/></li>
        </html:messages>
       </font>
      </ul>
    

    This code will iterate through the Struts messages collection that was generated during validation, displaying each error as a bulleted item.

  2. One more thing needs to be done before error messages can be displayed. Edit the application.properties file to add the following lines at the end:
    commentForm.userID=User name entry
    commentForm.email=Email entry
    commentForm.zipCode=Zip Code entry
    commentForm.comments=Comments entry
    

    These lines tell Struts what text to display corresponding to each form request parameter.

  3. This completes the example. To test it, rebuild the project and click the Execute in Browser button. Then click on Comment Submission Form. Click the Submit button without filling in any of the fields in the form. You should now see a bulleted list of errors in red at the top of the form. Correct the entries and click Submit again to see the thankyou.jsp page.

See also: