Creating advanced input forms using JSF and JavaScript with IBM Rational Application Developer V6

Creating complex validation on input forms no longer needs to be difficult, and no longer requires detailed knowledge of Java or the internals of JSF. With the release of Rational Application Developer V6, you can quickly and easily create forms involving complex validation using drag and drop.

Share:

Dan O’Connor (dan_o'connor@us.ibm.com), Software Engineer, IBM

Dan O'Connor is a developer in the WebSphere Studio Application Developer Web tooling team, currently working on the tooling for JavaServer Faces (JSF). He has worked on several different parts of the JSF tooling ranging from palette drag and drop actions to attributes view development. Before joining the WebSphere Studio team, Dan was a developer with the Lotus Global Product Development (GPD) team. Dan received his degree in Computer Engineering from the University of Limerick, Ireland.



05 January 2005

Introduction

IBM® Rational® Application Developer for WebSphere® Software Version 6 (hereafter called Rational Application Developer) offers several components that can help you create sophisticated input forms such as user registration forms. This technology is known as Input Assist. You set it up at design time, and at run time it generates components that assist the user. This article shows you how to create a user registration form from beginning to end.

This article assumes that you have Rational Application Developer installed, that you have experience developing Web pages using HTML, and a basic understanding of Java™.


Creating a JavaServer Faces Web project

  1. Launch Rational Application Developer and choose to create a new workspace.
  2. Switch to the Web perspective.
  3. Go to the File menu and create a new Dynamic Web Project.
  4. Give the project a name (I named mine userregisteration), and click Finish.
  5. Once the project is created, expand it in the Project Explorer view. Right mouse click on the WebContent folder. Select to create a new Faces JSP File. Name the file createnewuser.jsp. The createnewuser.jsp page will be displayed when creating a new user, analogous to the typical Web page that asks visitors to register.
  6. Close createnewuser.jsp. Right mouse click on the WebContent folder and select to create a new Faces JSP File.
  7. Name the file success.jsp.
  8. Close success.jsp. The success.jsp page is where users will be redirected to once they have successfully registered.
  9. Like you did in the previous two steps, create a new Faces JSP Page and name it failure.jsp. Close the jsp file. Users will be redirected to this failure.jsp page if user registration fails.

You now have the skeleton of a Web project for registering users. The next step is to create a database for storing user information.


Creating a user registration database

In this section I will show you how to create a Cloudscape database, and a table in that database that can be used for storing registered users.

  1. To start, download cloudscapedb.sql.
  2. Import the file into your workspace, placing it in the WebContent folder of your current project. Switch to the Data perspective and go to the Database Explorer view.
  3. Right-click in the view and choose to create a New Connection. Select Choose a database manager and JDBC driver:
    Figure 1: New database connection dialog
    Figure 1: New database connection dialog window
  4. Select Next.
  5. Select Cloudscape => V5.1 as the database manager.
  6. Select a location where you want to create your database; I choose a location within my workspace for the convenience of this article. The final segment of the path should not be an actual directory, but the desired location of the directory. The wizard will create the final segment of the path, and will create the database within that directory. In Figure 2, the USERS directory will not be created until the wizard has run. Select the default for all other fields; make sure to enter your OS user name and password in the field provided:
    Figure 2: Specifying the connection parameters
    Figure 2: Specifying the connection parameters window
  7. Click Finish. Select No when prompted if you want to copy metadata to a project folder.
  8. Return to the Web perspective. Right mouse click on cloudscapedb.sql. Choose to Deploy. Click Next until you get to the Database Connection dialog. Choose to use the existing connection, as shown in Figure 3:
    Figure 3: Database connection
    Figure 3: Database connection window
  9. Click Finish.
  10. Go to the Data perspective and select to refresh con1 in the Database Explorer. Expand con1. You should see a structure similar to Figure 4:
    Figure 4: USERS Database structure
    Figure 4: USERS Database structure window
  11. Return to the Web perspective.

You have now created a user registration database and are ready to develop a user registration page.


Creating a Web page for registering users

  1. In the Project Explorer view of the Web perspective navigate to the WebContent folder. Expand the folder and open the file named createnewuser.jsp that you created earlier. Delete the default text from the top of the page and type User Registration:. Format that text as a Heading 3 and select to center align.
  2. Drag and drop a Relational Record from the Data drawer of the palette. Name it addUser and select to Create controls for: Creating a new record as shown in Figure 5:
    Figure 5: Add Relational Record
    Figure 5: Add Relational Record window
  3. Click Next.
  4. Click New to select a new database connection. Choose Use Live connection, and select to use Con2. Click Finish and use TEST.USERS as the table, as shown in Figure 6:
    Figure 6: Relational Record Properties
    Figure 6: Relational Record Properties window
  5. Click Finish. Save the JSP page.
  6. At this stage controls will be automatically generated and will be put on the page. An HTML table will be created. There will only be text in the left column of the table. The right hand column of the table will have inputText fields.

    Click on the USERNAME inputText field. Go to the properties view, and click on the Validation tab. Click the checkbox so that Value is required. Set the minimum length to 6 characters. Also, select to Display validation error message in an error message control. Figure 7 shows what the Validation page should look like when complete:
    Figure 7: Username validation
    Figure 7: Username validation fields
  7. Go to the Behavior tab, and select to Validate field value in the browser. Figure 8 shows the completed Behavior page:
    Figure 8: Behavior tab for username
    Figure 8: Behavior tab for username fields
  8. Select the first message component on the page and go to the properties view for the component. Notice that the Id and Classes attributes aren't set. Set the id to some unique value, such as message1. Set the classes value to be message. You will need to set the id and classes attributes on all message components added through the properties views. Figure 9 shows how the first message component will look when set up properly:
    Figure 9: Message1 properties view
    Figure 9: Message1 properties view fields
  9. Click on the FIRSTNAME inputText field. As we did for USERNAME in the previous step, set the value as required on the validation tab, and set the control up to display validation error messages in an error message control. Do not set a minimum length. Set the behavior the same way as previously. Click on the second message component and set it up like the one above. However this time the Id attribute should be set to a unique value such as message2.
  10. Repeat step 5 for the LASTNAME inputText field, for the STREETADDR inputText field and for the CITYADDR inputText field.
  11. Click on the STATEADDR inputText field. Go to the attributes view. Select the Validation tab and set the maximum length to two characters. On the Behavior tab, select to Auto-advance to the next field, as shown in Figure 10:
    Figure 10: STATEADDR’s behavior tab
    Figure 10: STATEADDR’s behavior tab
  12. Click on the ZIPADDR inputText field. Go to the h:inputText tab of the attributes view. Change Format to Mask. Set the Mask attribute to #####. Select to Show prompt character and set the Prompt character to #. The end result is shown below in Figure 11.

    The Mask attribute is set on the convertMask converter. This converter expects users to input data in the format (pattern) specified in the mask attribute and then knows to translate the input into a basic string. Having pound signs (#) in the mask implies that the expected input are numbers, question marks (?) are used to denote alphabetical characters as the expected input. The prompt character is an attribute of the inputHelperAssist tag. At runtime JavaScript will be created by the inputHelperAssist tag that will prompt the user on what is expected as the value of the given field. Specifying # as the prompt character signals that at runtime # will appear in the text field by default for the pattern ##### which was specified as the mask attribute.

    Figure 11: ZIPADDR’s attributes view
    Figure 11: ZIPADDR’s attributes view

    As in previous steps, set the maximum length on the Validation tab to 5 characters and enable Auto-advance to the next field on the Behavior tab.

  13. Delete the PASSWORD inputText field and drag and drop an Input – Password component in its place. On the h:secret tab of the attributes view go to the Value field and press the button to the right of the field. This will bring up the bind to dialog. Expand the addUser node, expand the next addUser node, scroll down and select PASSWORD, click OK. Go to the Validation tab of the password field and set the minimum length to 6 characters and set the value to be required. Select some white space in the DOB (Date of birth) row of the table (i.e. select a space where there are no JSF controls). Go to the Table menu and select to insert a row above the current row, as shown in Figure 12:
    Figure 12: Add row menu
    Figure 12: Add row menu
  14. Drag and drop an Input – Password control into the right hand column of the new row. Do not bind this field to any value, it will be used for password verification purposes. On the Validation tab in the attributes view, set value as required. In the left hand column of the new row type Confirm Password:
  15. Click on the DOB inputText field. Set the Date style to Short. Enable the prompt character, using underscore (_) as the prompt character:
    Figure 13: DOB’s attributes view
    Figure 13: DOB’s attributes view
  16. Go to the validation tab. Note that there is a bug that sometimes prevents the validation tab from correctly updating. If you notice that the Validation page is not the validation page that corresponds to the converter that you are using, then simply switch to source mode and select the inputHelperAssist tag that your inputText component is currently using. This will force a UI update.
  17. Select the Value is required checkbox. Do the same for the Display validation error message in an error message control checkbox. For this particular registration page you want to validate that the person registering is over a certain age, in this example 18. To do that, use the now keyword, which translates to the moment in time when the JSP is run. You can use the following Expression Language (EL) expression to represent eighteen years:
    now-(((((1000*60)*60)*24)*365)*18)

    The minimum (and maximum) value of the dateTimeValidator takes milliseconds as its value, so all expressions dealing with the now keyword must be expressed in milliseconds. When finished your validation page should look like Figure 14:
    Figure 14: DOB’s Validation page
    Figure 14: DOB’s Validation page fields
  18. Return to design mode if necessary and save the page.
  19. Go to the Behavior tab and choose to Validate field value in the browser. Also select to Auto-advance to next field. Press the Additional behaviors can be supplied onsuccess and onerror events in the Quick Edit view button and go to the onerror event. Click on the event and then click on the JavaScript editor on the right hand side. Add the following line of JavaScript:
    Listing 1: Popup JavaScript
    alert("You must be at least 18 years old to register for this site");
  20. Save the page.
  21. Select the Submit button at the bottom of the page. In this exercise you want the information on the page to be validated during the submission of the page, this includes ensuring that the email address is of a valid format (i.e. contains an @ sign and has a dot (.) after the @ sign). You also want to ensure that the Password and Password Confirmation fields are the same. To do this you will need to write some very basic Java. After clicking on the submit button go to the Quick Edit View (QEV). You will see that the tooling has already created some auto-generated Java code. Place the cursor before the try keyword and press return 4 or 5 times. Change the code so it now looks like this:
    Listing 2: doAddUserUpdateAction()
    //Validate email address
        String email = (String) getText9().getValue();
        String retVal = "";
        boolean error = true;
        int index = -1;
    
        if (email != null) {
            index = email.indexOf("@");
        } else {
            error = false;
        }
        if (index != -1) {
            email = email.substring(index);
            index = email.indexOf(".");
            if (index != -1) {
                error = false;
            }
        }
        if (error) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                "Email address is invalid",
                "Email address should contain @ and be followed by a dot");
            getFacesContext().addMessage(getText9().getClientId(getFacesContext()), message);
            return retVal;
        }
        //Validate password
        String password1 = (String) getSecret1().getValue();
        String password2 = (String) getSecret2().getValue();
    
        if (!password1.equals(password2)) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Passwords need to be the same",
                "Password values should be the same");
    
            getFacesContext().addMessage(getSecret2().getClientId(getFacesContext()), message);
            return retVal;
        }
        // Old code, autogenerated by tooling.. Add the new return statements as
        // shown below..
        try {
            getAddUserMediator().applyChanges(getAddUser().getDataGraph().getRootObject());
            retVal = "success";
        } catch (Throwable e) {
            logException(e);
            if (e.getMessage().indexOf("it would have caused a duplicate key value 
                    in a unique or primary key constraint") != -1) {
                retVal = "duplicate";
            }
            SDOConnectionWrapper = null;
            return retVal;
        }
        SDOConnectionWrapper = null;
        return retVal;

    The above code assumes that the email field's id will be text9 and that the password fields' ids will be secret1 and secret2. You will will want to cross check those ids before copying the code above.

  22. Save the page. Click on the Submit button and go to the attributes view. Add a navigation rule (using the Add Rule button). Select success.jsp as the page to go to, when the outcome is named success and the action is
    #{pc_Createnewuser.doAddUserUpdateAction}
  23. Add another navigation rule (using the Add Rule button). Select failure.jsp as the page to go to, when the outcome is named duplicate and the action is:
    #{pc_Createnewuser.doAddUserUpdateAction}
  24. Click on the Error Messages component at the bottom of the page (above the Submit button). Go to the attributes view and select the radio button that forces the component to Show only error message not associated with a specific component.
  25. Go to the attributes view for h:form. Go to the Keyboard Assist tab. Select to have focus go to the first field on the page when the page is initially loaded, as shown in Figure 15:
    Figure 15: Keyboard assist
    Figure 15: Keyboard assist
  26. Rename the row names in the table so they look like the names in Table 1 below:

    Table 1: Table row names

    Original nameNew name
    UsernameUser Name (min 6 chars):
    FirstnameFirst Name:
    LastnameLast Name:
    StreetaddrStreet:
    CityaddrCity:
    StateaddrState:
    ZipaddrZIP:
    HomephoneHome Telephone:
    WorkphoneWork Telephone:
    Emaile-mail:
    PasswordPassword:
    Confirm PasswordConfirm password:
    DobDate of birth:

    The finished page is shown in Figure 16:

    Figure 16: Final version of createnewuser.jsp
    Figure 16: Final version of createnewuser.jsp
  27. Save and close the page. Open success.jsp. Type a congratulatory text on the page such as:
    Congratulations. You have successfully registered for our Web site.

    Save and close the page.
  28. Open failure.jsp. Type the following error message on the page:
    ERROR. The user name you selected is already in use, please choose another and register again.
  29. Save all pages and right mouse click on createnewuser.jsp and select Run the page on the server. When the page renders in the browser, notice that focus automatically jumps to the first field on the page.

To test your work, fill out the form but enter an invalid form of email address (for instance, one without the @ sign, or with no dot after the @ sign). Press submit and notice that an error message is added to the page. The same happens if the two passwords entered are not the same. Also notice that if you do not enter any value for the fields that were set as required and press submit an error will be generated. Likewise an error is generated after the submit button is pressed if a field is shorter than the minimum length entered in the validation tab of the attributes view. Finally try entering a date of birth that would imply the person registering was less than 18 years of age. Notice that a popup will appear stating that you need to be 18 years or older to register.


Exercise

Now that you have created an input form, an interesting exercise would be to create a page that would display all users for administrative purposes. Such a page is included in the WAR file that is linked above, at the top of this page. Please download that WAR file and use it as a reference.


Conclusion

As you can see from this article it is quiet easy to create advanced input forms with very little Java programming knowledge. There are many more such "helper" components that a Web site designer could use to make input forms more user friendly. Some of these components include the calendar helper that is available for date fields, a time helper for time fields, and a spinner/slider helper control for number fields. All of these components can be easily added through the attributes views.


Acknowledgements

The author would like to thank Yury Kats for reviewing this article.


Downloads

DescriptionNameSize
Code samplecloudscapedb.zip  ( HTTP | FTP )1 KB
Code sampleuserregisteration.zip  ( HTTP | FTP )866 KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=32426
ArticleTitle=Creating advanced input forms using JSF and JavaScript with IBM Rational Application Developer V6
publish-date=01052005