V4.1
                                                                                                   Instructor Exercises Guide



EXempty   Exercise 10.Create a Struts Application

          What this exercise is about
                                  This lab introduces the Web Diagram editor as a Struts application
                                  development tool. It helps you design Struts JSP pages, action
                                  mappings and form beans visually in a Web Diagram. Implement each
                                  part of the Struts application using the Web development tools. Lastly,
                                  test the Struts Web application in the Integrated Test Environment.


          What you should be able to do
                                  At the end of the lab, you should be able to:
                                   • Enable Struts functionality on a dynamic Web project.
                                   • Configure a resource bundle for storing externalized strings.
                                   • Add Struts elements to JSP pages.
                                   • Add an action through the Web diagram editor.
                                   • Configure a validator to perform simple input field checking.


          Introduction
                                  In previous exercises, you could perform user searches and renew
                                  items for any patron in the library database. A better use case would
                                  be to have each patron access his or her own list of borrowed items
                                  only. Use Struts to add a login page for patrons to enter the user ID
                                  and password before returning a list of borrowed items.
                                  This exercise also demonstrates the error handling facilities provided
                                  by Struts. Using the validator in the action class, the Struts application
                                  checks whether the user ID and password fields are of the correct
                                  type. After passing validation, the Library application checks user ID
                                  and password against credentials stored in the database. Valid user
                                  credentials trigger the success Struts action, revealing the item search
                                  results. Invalid user credentials trigger the failure action and returns
                                  the error page.
                                  In a real world scenario, the login page should rely on WebSphere
                                  security settings for the authentication mechanism and user directory.
                                  This example relies on the library application itself to return the user ID
                                  and password.



          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application     10-1
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide



Requirements
                        Before starting this lab, you must set up the LibraryWeb Web project
                        and the LibraryUtility Java project according to the instructions in
                        Exercise 3.
                        This exercise requires several code fragments and files. Make sure
                        that these files appear in the <LAB_FILES>Struts directory before
                        starting the lab.


Instructor exercise overview
This exercise focuses on the Web Diagram editor as a way to visually compose a Struts
Web application. Using the diagram, the student realizes three JSP pages:
         • login.jsp, a form for the user to enter his or her user ID and password.
         • error.jsp, a warning page notifying the patron that the login credentials did not
           match the values in the database.
         • search.jsp, a Struts JSP page that returns a list of borrowed items for the
           currently logged in patron.
The main component is the Login action class, which verified the login information and
triggers the search page. The /Login action mapping routes Web application calls to the
Login action class. Depending on authentication success or failure, the Struts engine
forwards control to the search or error page.
This lab also demonstrates the validation capabilities in Struts. Simple checks to the user
ID and password bounce the user back to the login page, minimizing the need to check the
actual user database if a field is left blank or if it has the wrong syntax.
Lastly, this design uses a form bean to hold the login credentials as it passes from each
node in the Struts application.
Students should not encounter problems running this lab, given the detailed instructions
and accompanying screenshots. Some students unfamiliar with visual tools might find it
difficult to create the Struts application using the Page Designer. Encourage them to
experiment with the tool and use the ‘undo’ tool to retry.
Also encourage students to examine the code snippets throughout the lab. Understanding
the logic behind the action class is key to understanding how this Struts application works.




10-2 Developing Web Applications                                                  © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   Exercise instructions
          Preface
          The lab exercises in this course are designed to run in sequence. If you have skipped one
          of the previous labs, you must follow the steps in Appendix A before starting this
          lab.
          The following references in the exercise instructions represent directory locations in your
          workstation:
                   • <LAB_FILES>: c:IBMSDP70




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application     10-3
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide



10.1. Enable Struts Support on LibraryWeb Web Project
Before you can start building your Struts application, you must enable support for Struts in
the Web project properties. This step adds the necessary support JAR files into the project.
After you enable Struts, configure the level of Struts support in the Struts settings dialog.
__ 1. Stop the test server if it is running. In the Servers view, right-click the server and
      select Stop.
__ 2. Enable the Struts facet in LibraryWeb.
    __ a. Switch to the Web perspective.
    __ b. In Project Explorer, right-click LibraryWeb and select Properties.
    __ c. In the Properties for LibraryWeb dialog, type facet in the search field on the
          top left. Select Project Facets.




    __ d. Click Add/Remove Project Facets.




10-4 Developing Web Applications                                                  © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty       __ e. In the Add/Remove Project Facets dialog, select Struts. Click Next.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application     10-5
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ f.   On the Struts Settings page, select the Override default settings option.
            Change the Default Java package prefix to com.ibm.library.struts.




    __ g. Click Finish, then click OK.




10-6 Developing Web Applications                                                  © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   __ 3. Expand LibraryWeb Java Resources: src. Notice the new
                ApplicationResources.properties file under com.ibm.library.struts.resources,
                as well as a number of Struts-related JAR files added to the project.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application     10-7
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide



10.2. Create the Application Resources File
The application resources properties file holds text strings that appear in Struts JSP files.
With all strings in one location, the task of internationalization becomes much simpler.
Instead of translating strings and changing formats to suit the locale in each JSP page,
simply modify one properties file.
Add a definition for several text strings in the properties file. You will use these strings in
future Struts JSP files.
__ 4. Import a set of text strings into the properties file.
    __ a. Double-click LibraryWeb Java Resources: src
            com.ibm.library.struts.resources ApplicationResources.properties to
          open it in an editor.
    __ b. Replace the contents in the ApplicationResources.properties file with those
          found in <LAB_FILES>Strutssnippetssnippet01.txt.
            errors.header=<ul>
            errors.footer=</ul>
            index.title=IBM Library System
            button.login=Login
            global.field.userid=User ID
            global.field.password=Password
            error.login.nouserid=<li>You must enter a User ID.
            error.login.nointuserid=<li>The User ID must be an integer.
            error.login.nopassword=<li>You must enter a Password.
            error.login.failed=<li>Invalid User ID and/or Password entered.
            error.login.exception=<li>Exception occurred in action.
    __ c. Save and close the ApplicationResources.properties file.




10-8 Developing Web Applications                                                  © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   10.3. Model the Struts Pages in a Web Diagram
          One of the features of the Web Diagram is to model the runtime behavior of a Struts
          application. Simply add the pages and map transitions between pages using actions.
          For the LibraryWeb application, create a login page that takes a patron name and
          password. After successfully logging in, retrieve a list of borrowed items for that patron.
          Redirect users to an error page if the user name and password are incorrect.
          __ 5. Open the Web Diagram and design the Struts application.
              __ a. In the Project Explorer, double-click LibraryWeb Web Diagram to open it in
                    the editor. Close the Welcome to the Web Diagram Editor note.

                      Information

          You will now use the Palette view on the right to layout your JSP pages, beans, and Struts
          Actions.




          __ 6. Create the Web Page objects.
              __ a. Expand the Web Parts drawer in the Palette view and click the Web Page
                    component. Click the left side of the diagram editor to drop the Web Page node.
              __ b. Name the Web Page node login.jsp and press ENTER.



          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application     10-9
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide




            Note

By default, components in the Web Diagram are created automatically. For example, press
SHIFT-ENTER after you have changed the Web Page name in order to not realize the
page.



    __ c. Create another Web Page node and name it error.jsp.




    __ d. In the Project Explorer view, expand LibraryWeb                       WebContent. Drag
          listitems.jsp onto the diagram editor.




__ 7. Create an Action object for the verification of the User ID and Password.
    __ a. In the Palette view, under the Web Parts drawer, click Struts Action. Click in the
          center of the JSP pages to drop the action. Note that the button that appears on
          the action allows you to map to existing actions.




10-10 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty       __ b. Name the Struts Action /Login and press ENTER.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-11
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide



10.4. Connect Struts Objects
Create the connection between nodes. A connection is a line that represents either logic
flow or data flow between two Struts objects.
__ 8. Create a Struts Form link starting from the login.jsp page to the /Login Struts
      Action. When the user clicks Login, the /Login Struts Action will be invoked.
    __ a. In the Web diagram, click the login.jsp Web page.




    __ b. Drag the connection handle to the /Login Struts Action.




    __ c. While still dragging and when the cursor changes into a black arrow, click the
          /Login Struts Action and select Struts Form.




            Note

A /Login Struts Form link has been added to login.jsp..




The link in between the two nodes is now solid grey.




10-12 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   The login.jsp Web Page now contains a Struts HTML form element with an action of
          /Login. The form also contains a Struts HTML submit button.



          __ 9. The /Login Struts action needs to access the userid and password from login.jsp.
                Add a LoginForm Form bean to the /Login Struts action.
              __ a. Hover over the /Login Struts action and click the Add Form Bean icon in the
                    flyout.




              __ b. Click New in the Form Bean Selection dialog.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-13
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ c. In the New Form-Bean dialog, type LoginForm for the Form Bean Name.




    __ d. Click Next.
    __ e. The next page allows you to import fields from existing forms. Skip this page by
          clicking Next.




10-14 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty       __ f.   On the Create new fields for your ActionForm class page, add userid and
                      password strings. Click Add and type userid for the Name. Click Add again
                      and type password for the NAME.




              __ g. Click Finish.
              __ h. Click OK.
          __ 10. The /Login Struts action will be called when the user clicks the Login button in the
                 login.jsp. Add an Action Input from the /Login Struts Action to the login.jsp. This is
                 in case the login information is not formatted correctly. For example, the password is
                 empty or too short.
              __ a. Hover over the /Login Struts Action and drag the connection handle over to the
                    login.jsp.
              __ b. Click login.jsp and select Action Input.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-15
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ c. The Web Diagram should look as follows:




__ 11. When the /Login Struts Action runs, the result may be success or failure. Add a
       local forward, representing success, from the /Login Struts Action to listitems.jsp.
       Add a local forward, representing failure, from the /Login Struts Action to error.jsp.
    __ a. Hover over the /Login Struts Action and drag the connection handle over to the
          listitems.jsp. Select Local Forward from the popup menu. A link named
          success will be added to the /Login Struts Action.
    __ b. Hover over the /Login Struts Action and drag the connection handle over to the
          error.jsp. Select Local Forward from the popup menu. A link named failure will
          be added to the /Login Struts Action.




    __ c. Save the Web diagram before continuing.




10-16 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   10.5. Implement the JSP Pages
          Start by implementing the login.jsp and error.jsp Web pages.
          __ 12. Use Page Designer to implement the login.jsp page.
              __ a. In the diagram editor, double-click the login.jsp node.
              __ b. Switch the Page Designer to the Design tab.
          __ 13. The tool has added an <html:form> tag element with /Login as the action. As the
                 message in the <div> indicates, cut the form from the <div> and paste it below. Add
                 the page heading title to the login.jsp page, based on a string from the properties
                 file.
              __ a. In the Outline view, drag the html:form element and drop it below the <body> tag.




              __ b. In the Outline view, right-click the <div> tag, below the html:form, and select
                    Remove.
          __ 14. Add the page heading title to the login.jsp page, based on a string from the
                 properties file.
              __ a. In Page Designer, click inside the form to select it.




              __ b. Select Format            Paragraph        Heading 1 from the main menu.
              __ c. In the Palette view, expand the Struts Bean Tags drawer and double-click the
                    Message component.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-17
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ d. In the Properties view, the bean:message tab should be automatically selected,
          type index.title as the Direct Key. Press ENTER to commit your changes.
          Verify that the text IBM Library System appears in the login.jsp file.




            Note

Question marks will appear to the left of your title if Page Designer does not recognize the
custom tag being inserted into the page.




If this situation occurs, verify that the following custom tag prefix declarations appear in the
source of the JSP file:




10-18 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   __ 15. Add a Struts error message section below the title heading.
              __ a. Position the cursor after the IBM Library System heading and press ENTER to
                    move the cursor to the next line.
              __ b. Select Format            Paragraph        Normal from the main menu.
              __ c. In the Palette view, expand the Struts HTML Tags drawer, double-click the
                    Errors component. A list of sample error messages should now appear in the
                    Page Designer.




          __ 16. Add the user ID label, password label, and form fields to the JSP file.
              __ a. In Page Designer, click on the Errors component and press the down arrow key
                    to move the cursor to the next line.
              __ b. In the Palette view, double-click the Message component in the Struts Bean
                    Tags drawer. Type global.field.userid in the Properties view under Direct
                    Key.
              __ c. Press the SPACE key to add a space after the Message component.
              __ d. Double-click the Message component in the Palette view again to insert another
                    text label. This time type global.field.password in the Direct Key field
                    under the bean:message tab in the Properties view.
              __ e. Position the cursor in between the two messages in Page Designer.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-19
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ f.   In the Palette view, double-click the Text component in the Struts HTML Tags
            drawer.
    __ g. In the Properties view, the html:text tab should be automatically selected, type
          userid in the Property field.




    __ h. In the Page Designer, press ENTER to move the Password label to the next
          line.




    __ i.   Position the cursor after the Password label. You can do this by selecting the
            Password label and pressing the right arrow key.
    __ j.   Double-click the Password component under the Struts HTML Tags drawer in
            the Palette view. In the Properties view, under the html:password tab, type
            password in the Property field.




__ 17. Set the submit button to use a Struts Message component for the label.
    __ a. Select the Submit Query button.
    __ b. In the Palette view, double-click the Message component under Struts Bean
          Tags.




10-20 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty       __ c. The button should now have Missing attribute(s): key name as the label. In the
                    Outline view, select bean:message under the html:submit node.




              __ d. In the Property view, the Message tab appears. Type button.login in the
                    Direct Key field.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-21
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ e. The label on the button should change to Login. Note that if the label does not
          change, save your changes, close Page Designer and open it again.




    __ f.   Save the changes.
__ 18. Examine the Struts JSP tags in the login.jsp source view.
    __ a. Switch to the Source tab of the page designer.




__ 19. Implement the error.jsp file.
    __ a. Switch to the Web Diagram editor and double-click the error.jsp node.
    __ b. In the Page Designer, click the Source tab. Add the following content in between
          the <body> </body> tags. Note that the content can be copied from
          <LAB_FILES>Strutssnippetssnippet02.txt.
            <h1><bean:message key="index.title"/></h1>
            <h2>Error Page</h2>
            <p>
            <html:errors/>
            <p>
            <a href="login.jsp"><b>Return to Login Page</b></a>


10-22 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty       __ c. Click the Preview tab to see the results.




              __ d. Save and close error.jsp.




          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-23
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide



10.6. Implement the Action Form Class
Implement the action form that processes the user ID and password from the login JSP file.
This Form Bean class contains a member instance field and accessor methods (getters
and setters) for each field in the input form. It also provides simple field checking.

            Note

The terms Struts form, action form, and form bean are synonymous.



__ 20. Implement the validate method in the LoginForm.java action form class.
    __ a. Open the Web Diagram, double-click the LoginForm inside of the /Login Struts
          action.
    __ b. When the LoginForm was created, the wizard filled in most of the elements in the
          class. This included the two fields (userid and password) and their getters and
          setters. Scroll down in the file to the ActionErrors validate method and
          replace the method body with code found in
          <LAB_FILES>Strutssnippetssnippet03.txt.
            ActionErrors errors = new ActionErrors();
            if ((getUserid() == null) || (getUserid().length() == 0)) {
               errors.add("userid", new ActionError("error.login.nouserid"));
            } else {
               try {
                  Integer.parseInt(getUserid());
               } catch (Exception e) {
                  errors.add(
                     "userid",
                     new ActionError("error.login.nointuserid"));
               }
            }
            if ((getPassword() == null) || (getPassword().length() == 0)) {
               errors.add("password", new
                  ActionError("error.login.nopassword"));
            }
            return errors;
    __ c. Use Source Organize Imports to fix any errors related to missing imports.
          When prompted, choose org.apache.struts.action.ActionError in the
          Organize Imports dialog.
    __ d. Save and close LoginForm.java.




10-24 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   10.7. Implement Action Mapping and the Action Class
          The next step is to implement the /Login action mapping and the LoginAction class. The
          LoginAction class will be invoked with the data from the login form. This class can be used
          to implement the calls to business logic. It can also be used to make sure that the state and
          conditions are correct for invoking the business logic. In this exercise, it will be used to
          authenticate the user's ID and password.
          __ 21. Implement the execute method in the LoginAction class.
              __ a. Open the Web Diagram, double-click the /Login Struts Action node.
              __ b. In the Java editor for the LoginAction class, replace the execute method with
                    the one found in <LAB_FILES>Strutssnippetssnippet04.txt.
                      public ActionForward execute(ActionMapping mapping,
                         ActionForm form, HttpServletRequest request,
                         HttpServletResponse response)
                         throws Exception {

                      ActionErrors errors =            new ActionErrors();
                      ActionForward forward            = new ActionForward();
                      HttpSession session =            request.getSession();
                      LoginForm loginForm =            (LoginForm) form;

                      try {
                         int id = Integer.parseInt(loginForm.getUserid());
                         String password = loginForm.getPassword();
                         Patron patron = Patron.findById(id);
                         if (patron==null || !password.equals(patron.getPassword())) {
                               errors.add(
                                  "login", new ActionError("error.login.failed")
                               );
                            }
                            ArrayList<LoanedCopy> items = new ArrayList<LoanedCopy>();
                            Collection copies = patron.getCopies();
                            Iterator copyIt = copies.iterator();
                            while (copyIt.hasNext()) {
                               Copy copy = (Copy)copyIt.next();
                               Item item = copy.getItem();
                               LoanedCopy loanedCopy = new LoanedCopy(copy.getItemId(),
                                  copy.getCopyNumber(), item.getTitle(),
                                  item.getAuthor(), copy.getDue(),
                                  copy.getTimesRenewed());
                               items.add(loanedCopy);
                            }
                            session.setAttribute("PATRON", patron);

          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-25
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


                   session.setAttribute("itemList", items);
                } catch (Exception e) {
                   errors.add(
                      "login", new ActionError("error.login.exception")
                   );
                }

                if (!errors.isEmpty()) {
                   saveErrors(request, errors);
                   forward = mapping.findForward("failure");
                } else {
                   forward = mapping.findForward("success");
                }

                return (forward);
            }
    __ c. Use Source Organize Imports to fix any errors that may come up. When
          prompted, choose:
             - java.util.Iterator
             - java.util.Collection
             - com.ibm.libary.model.Copy
             - com.ibm.libary.model.Item
    __ d. Save and close LoginAction.java.




10-26 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.
V4.1
                                                                                                   Instructor Exercises Guide



EXempty   10.8. Test the Struts Pages
          At this point, you have implemented the login feature in the LibraryWeb application. Test
          this new feature by running the LibraryWeb application in the Integrated Test Environment.
          Since you have added the Library enterprise application to the server in a previous
          exercise, you only need to run the new login page on the server.
          __ 22. Test the user ID and password validation features in the Login action class.
              __ a. In the Project Explorer view, right-click LibraryWeb WebContent                             login.jsp
                    and select Run As Run on Server.
              __ b. If the Run On Server dialog opens, click Finish.
              __ c. Once the login page loads in the browser, type abc in the User ID field, then
                    click Login.
              __ d. You should be returned to the login page again, with two error messages
                    showing at the top.




          __ 23. Test the failure navigation rule in the Login action class.
              __ a. Type 2 in User ID and password in Password, click Login.
              __ b. You should be forwarded to the error page, with a message noting that the User
                    ID/Password pair is invalid.




              __ c. Click Return to Login Page to return.
          __ 24. Test the success navigation rule in the Login action class.
              __ a. This time in the login page, type 2 in User ID and vogel in Password. Click
                    Login.

          © Copyright IBM Corp. 2004, 2007                                 Exercise 10. Create a Struts Application    10-27
                                      Course materials may not be reproduced in whole or in part
                                             without the prior written permission of IBM.
Instructor Exercises Guide


    __ b. You should now be successfully forwarded to the item list page and be able to
          make renew requests.




End of exercise




10-28 Developing Web Applications                                                 © Copyright IBM Corp. 2004, 2007
                             Course materials may not be reproduced in whole or in part
                                    without the prior written permission of IBM.

More Related Content

PPT
3) web development
PPT
7) packaging and deployment
PPT
web development
PDF
Spring Framework -I
PDF
Spring Framework - III
PPT
Struts Introduction Course
PDF
Oracle ADF 11g Tutorial
PPT
Oaf development-guide
3) web development
7) packaging and deployment
web development
Spring Framework -I
Spring Framework - III
Struts Introduction Course
Oracle ADF 11g Tutorial
Oaf development-guide

What's hot (19)

PPS
14 asp.net session20
PDF
Overview of JEE Technology
PDF
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
PPSX
01 asp.net session01
PPT
Struts N E W
PDF
37727897 Oaf Basics
DOCX
Int quest
PPT
Oracle Apex Overview
DOCX
Srikanth Kumar SharePoint Developer
PPTX
Pragmatic orchard
PDF
Jdev handbook-ch01-130992
DOCX
Struts notes
PDF
Exchange Server 2013 and SharePoint Server 2013 Integration
PDF
Example User Stories Specification for ReqView
PDF
OrchardCMS module development
DOCX
Tutorial 1
PDF
Spring Framework-II
PPSX
Oracle ADF Overview for Beginners
DOCX
Miguel Alberto Flores Torres AM (1)
14 asp.net session20
Overview of JEE Technology
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
01 asp.net session01
Struts N E W
37727897 Oaf Basics
Int quest
Oracle Apex Overview
Srikanth Kumar SharePoint Developer
Pragmatic orchard
Jdev handbook-ch01-130992
Struts notes
Exchange Server 2013 and SharePoint Server 2013 Integration
Example User Stories Specification for ReqView
OrchardCMS module development
Tutorial 1
Spring Framework-II
Oracle ADF Overview for Beginners
Miguel Alberto Flores Torres AM (1)
Ad

Viewers also liked (9)

PPT
Chapter 3.1
PDF
Desain pemodelan grafik - Tugas 2
PDF
LEI and Corporate Actions by Ontolgy2
PDF
Speciale programmatic 2016
PDF
Cat paper (cat2)_www.fellowbuddy.com
PDF
Presentación del curso spc
PDF
Go Vegan Presentation
PPTX
kinesiology and biomechanics ppt 03
PPTX
Introduction to Data Management Maturity Models
Chapter 3.1
Desain pemodelan grafik - Tugas 2
LEI and Corporate Actions by Ontolgy2
Speciale programmatic 2016
Cat paper (cat2)_www.fellowbuddy.com
Presentación del curso spc
Go Vegan Presentation
kinesiology and biomechanics ppt 03
Introduction to Data Management Maturity Models
Ad

Similar to Lab 5a) create a struts application (20)

PDF
Lab 7b) test a web application
PDF
Lab 5b) create a java server faces application
PDF
Lab 7a) debug a web application
PDF
Lab 4) working with databases
PDF
Step By Step Guide For Buidling Simple Struts App Speakernoted
PDF
Lab 2) develop a java application
PDF
Lab 3) create a web application
PDF
The 2014 Decision Makers Guide to Java Web Frameworks
PDF
F7 wc9 zu3701lsg_ai
PPTX
jDriver Presentation
PPT
Struts 2-overview2
PPT
Struts 2 Overview
PDF
Building-with-React-Native-Dont-Make-These-Mistakes.pdf
PPTX
Frameworks in java
ODP
eXo Platform SEA - Play Framework Introduction
PDF
Enhancing Website and Application Testing with Java Scrapers.pdf
PDF
Lab 6) package and deploy a j2 ee application
PDF
Part 6 debugging and testing java applications
PDF
Struts An Open-source Architecture for Web Applications
PPT
Struts 2-overview2
Lab 7b) test a web application
Lab 5b) create a java server faces application
Lab 7a) debug a web application
Lab 4) working with databases
Step By Step Guide For Buidling Simple Struts App Speakernoted
Lab 2) develop a java application
Lab 3) create a web application
The 2014 Decision Makers Guide to Java Web Frameworks
F7 wc9 zu3701lsg_ai
jDriver Presentation
Struts 2-overview2
Struts 2 Overview
Building-with-React-Native-Dont-Make-These-Mistakes.pdf
Frameworks in java
eXo Platform SEA - Play Framework Introduction
Enhancing Website and Application Testing with Java Scrapers.pdf
Lab 6) package and deploy a j2 ee application
Part 6 debugging and testing java applications
Struts An Open-source Architecture for Web Applications
Struts 2-overview2

More from techbed (20)

PDF
1456.base boot
PDF
1455.ata atapi standards - 1-7
PDF
1454.ata features
PPT
1432.encoding concepts
PDF
Flash cs4 tutorials_2009
PDF
Photoshop tut
PDF
What is struts_en
PDF
Part 7 packaging and deployment
PDF
First java-server-faces-tutorial-en
PDF
Part 5 running java applications
PDF
Part 4 working with databases
PDF
Part 3 web development
PDF
Part 2 java development
PDF
Part 1 workbench basics
PDF
Lab 1) rad installation
PPT
6) debugging and testing
PPT
5) running applications
PPT
4) databases
PPT
2009 ibm academic initiative
PPT
2) java development
1456.base boot
1455.ata atapi standards - 1-7
1454.ata features
1432.encoding concepts
Flash cs4 tutorials_2009
Photoshop tut
What is struts_en
Part 7 packaging and deployment
First java-server-faces-tutorial-en
Part 5 running java applications
Part 4 working with databases
Part 3 web development
Part 2 java development
Part 1 workbench basics
Lab 1) rad installation
6) debugging and testing
5) running applications
4) databases
2009 ibm academic initiative
2) java development

Recently uploaded (20)

PPTX
Climate Change and Its Global Impact.pptx
PDF
Civil Department's presentation Your score increases as you pick a category
PDF
semiconductor packaging in vlsi design fab
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
International_Financial_Reporting_Standa.pdf
PDF
plant tissues class 6-7 mcqs chatgpt.pdf
PDF
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
PPTX
Education and Perspectives of Education.pptx
PDF
1.Salivary gland disease.pdf 3.Bleeding and Clotting Disorders.pdf important
PPTX
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
PDF
HVAC Specification 2024 according to central public works department
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
Journal of Dental Science - UDMY (2020).pdf
PDF
CRP102_SAGALASSOS_Final_Projects_2025.pdf
PDF
M.Tech in Aerospace Engineering | BIT Mesra
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PPTX
Module on health assessment of CHN. pptx
PPTX
RIZALS-LIFE-HIGHER-EDUCATION-AND-LIFE-ABROAD.pptx
Climate Change and Its Global Impact.pptx
Civil Department's presentation Your score increases as you pick a category
semiconductor packaging in vlsi design fab
FORM 1 BIOLOGY MIND MAPS and their schemes
International_Financial_Reporting_Standa.pdf
plant tissues class 6-7 mcqs chatgpt.pdf
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
Education and Perspectives of Education.pptx
1.Salivary gland disease.pdf 3.Bleeding and Clotting Disorders.pdf important
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
HVAC Specification 2024 according to central public works department
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
Journal of Dental Science - UDMY (2020).pdf
CRP102_SAGALASSOS_Final_Projects_2025.pdf
M.Tech in Aerospace Engineering | BIT Mesra
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
Cambridge-Practice-Tests-for-IELTS-12.docx
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Module on health assessment of CHN. pptx
RIZALS-LIFE-HIGHER-EDUCATION-AND-LIFE-ABROAD.pptx

Lab 5a) create a struts application

  • 1. V4.1 Instructor Exercises Guide EXempty Exercise 10.Create a Struts Application What this exercise is about This lab introduces the Web Diagram editor as a Struts application development tool. It helps you design Struts JSP pages, action mappings and form beans visually in a Web Diagram. Implement each part of the Struts application using the Web development tools. Lastly, test the Struts Web application in the Integrated Test Environment. What you should be able to do At the end of the lab, you should be able to: • Enable Struts functionality on a dynamic Web project. • Configure a resource bundle for storing externalized strings. • Add Struts elements to JSP pages. • Add an action through the Web diagram editor. • Configure a validator to perform simple input field checking. Introduction In previous exercises, you could perform user searches and renew items for any patron in the library database. A better use case would be to have each patron access his or her own list of borrowed items only. Use Struts to add a login page for patrons to enter the user ID and password before returning a list of borrowed items. This exercise also demonstrates the error handling facilities provided by Struts. Using the validator in the action class, the Struts application checks whether the user ID and password fields are of the correct type. After passing validation, the Library application checks user ID and password against credentials stored in the database. Valid user credentials trigger the success Struts action, revealing the item search results. Invalid user credentials trigger the failure action and returns the error page. In a real world scenario, the login page should rely on WebSphere security settings for the authentication mechanism and user directory. This example relies on the library application itself to return the user ID and password. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-1 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 2. Instructor Exercises Guide Requirements Before starting this lab, you must set up the LibraryWeb Web project and the LibraryUtility Java project according to the instructions in Exercise 3. This exercise requires several code fragments and files. Make sure that these files appear in the <LAB_FILES>Struts directory before starting the lab. Instructor exercise overview This exercise focuses on the Web Diagram editor as a way to visually compose a Struts Web application. Using the diagram, the student realizes three JSP pages: • login.jsp, a form for the user to enter his or her user ID and password. • error.jsp, a warning page notifying the patron that the login credentials did not match the values in the database. • search.jsp, a Struts JSP page that returns a list of borrowed items for the currently logged in patron. The main component is the Login action class, which verified the login information and triggers the search page. The /Login action mapping routes Web application calls to the Login action class. Depending on authentication success or failure, the Struts engine forwards control to the search or error page. This lab also demonstrates the validation capabilities in Struts. Simple checks to the user ID and password bounce the user back to the login page, minimizing the need to check the actual user database if a field is left blank or if it has the wrong syntax. Lastly, this design uses a form bean to hold the login credentials as it passes from each node in the Struts application. Students should not encounter problems running this lab, given the detailed instructions and accompanying screenshots. Some students unfamiliar with visual tools might find it difficult to create the Struts application using the Page Designer. Encourage them to experiment with the tool and use the ‘undo’ tool to retry. Also encourage students to examine the code snippets throughout the lab. Understanding the logic behind the action class is key to understanding how this Struts application works. 10-2 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 3. V4.1 Instructor Exercises Guide EXempty Exercise instructions Preface The lab exercises in this course are designed to run in sequence. If you have skipped one of the previous labs, you must follow the steps in Appendix A before starting this lab. The following references in the exercise instructions represent directory locations in your workstation: • <LAB_FILES>: c:IBMSDP70 © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-3 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 4. Instructor Exercises Guide 10.1. Enable Struts Support on LibraryWeb Web Project Before you can start building your Struts application, you must enable support for Struts in the Web project properties. This step adds the necessary support JAR files into the project. After you enable Struts, configure the level of Struts support in the Struts settings dialog. __ 1. Stop the test server if it is running. In the Servers view, right-click the server and select Stop. __ 2. Enable the Struts facet in LibraryWeb. __ a. Switch to the Web perspective. __ b. In Project Explorer, right-click LibraryWeb and select Properties. __ c. In the Properties for LibraryWeb dialog, type facet in the search field on the top left. Select Project Facets. __ d. Click Add/Remove Project Facets. 10-4 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 5. V4.1 Instructor Exercises Guide EXempty __ e. In the Add/Remove Project Facets dialog, select Struts. Click Next. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-5 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 6. Instructor Exercises Guide __ f. On the Struts Settings page, select the Override default settings option. Change the Default Java package prefix to com.ibm.library.struts. __ g. Click Finish, then click OK. 10-6 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 7. V4.1 Instructor Exercises Guide EXempty __ 3. Expand LibraryWeb Java Resources: src. Notice the new ApplicationResources.properties file under com.ibm.library.struts.resources, as well as a number of Struts-related JAR files added to the project. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-7 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 8. Instructor Exercises Guide 10.2. Create the Application Resources File The application resources properties file holds text strings that appear in Struts JSP files. With all strings in one location, the task of internationalization becomes much simpler. Instead of translating strings and changing formats to suit the locale in each JSP page, simply modify one properties file. Add a definition for several text strings in the properties file. You will use these strings in future Struts JSP files. __ 4. Import a set of text strings into the properties file. __ a. Double-click LibraryWeb Java Resources: src com.ibm.library.struts.resources ApplicationResources.properties to open it in an editor. __ b. Replace the contents in the ApplicationResources.properties file with those found in <LAB_FILES>Strutssnippetssnippet01.txt. errors.header=<ul> errors.footer=</ul> index.title=IBM Library System button.login=Login global.field.userid=User ID global.field.password=Password error.login.nouserid=<li>You must enter a User ID. error.login.nointuserid=<li>The User ID must be an integer. error.login.nopassword=<li>You must enter a Password. error.login.failed=<li>Invalid User ID and/or Password entered. error.login.exception=<li>Exception occurred in action. __ c. Save and close the ApplicationResources.properties file. 10-8 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 9. V4.1 Instructor Exercises Guide EXempty 10.3. Model the Struts Pages in a Web Diagram One of the features of the Web Diagram is to model the runtime behavior of a Struts application. Simply add the pages and map transitions between pages using actions. For the LibraryWeb application, create a login page that takes a patron name and password. After successfully logging in, retrieve a list of borrowed items for that patron. Redirect users to an error page if the user name and password are incorrect. __ 5. Open the Web Diagram and design the Struts application. __ a. In the Project Explorer, double-click LibraryWeb Web Diagram to open it in the editor. Close the Welcome to the Web Diagram Editor note. Information You will now use the Palette view on the right to layout your JSP pages, beans, and Struts Actions. __ 6. Create the Web Page objects. __ a. Expand the Web Parts drawer in the Palette view and click the Web Page component. Click the left side of the diagram editor to drop the Web Page node. __ b. Name the Web Page node login.jsp and press ENTER. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-9 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 10. Instructor Exercises Guide Note By default, components in the Web Diagram are created automatically. For example, press SHIFT-ENTER after you have changed the Web Page name in order to not realize the page. __ c. Create another Web Page node and name it error.jsp. __ d. In the Project Explorer view, expand LibraryWeb WebContent. Drag listitems.jsp onto the diagram editor. __ 7. Create an Action object for the verification of the User ID and Password. __ a. In the Palette view, under the Web Parts drawer, click Struts Action. Click in the center of the JSP pages to drop the action. Note that the button that appears on the action allows you to map to existing actions. 10-10 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 11. V4.1 Instructor Exercises Guide EXempty __ b. Name the Struts Action /Login and press ENTER. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-11 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 12. Instructor Exercises Guide 10.4. Connect Struts Objects Create the connection between nodes. A connection is a line that represents either logic flow or data flow between two Struts objects. __ 8. Create a Struts Form link starting from the login.jsp page to the /Login Struts Action. When the user clicks Login, the /Login Struts Action will be invoked. __ a. In the Web diagram, click the login.jsp Web page. __ b. Drag the connection handle to the /Login Struts Action. __ c. While still dragging and when the cursor changes into a black arrow, click the /Login Struts Action and select Struts Form. Note A /Login Struts Form link has been added to login.jsp.. The link in between the two nodes is now solid grey. 10-12 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 13. V4.1 Instructor Exercises Guide EXempty The login.jsp Web Page now contains a Struts HTML form element with an action of /Login. The form also contains a Struts HTML submit button. __ 9. The /Login Struts action needs to access the userid and password from login.jsp. Add a LoginForm Form bean to the /Login Struts action. __ a. Hover over the /Login Struts action and click the Add Form Bean icon in the flyout. __ b. Click New in the Form Bean Selection dialog. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-13 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 14. Instructor Exercises Guide __ c. In the New Form-Bean dialog, type LoginForm for the Form Bean Name. __ d. Click Next. __ e. The next page allows you to import fields from existing forms. Skip this page by clicking Next. 10-14 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 15. V4.1 Instructor Exercises Guide EXempty __ f. On the Create new fields for your ActionForm class page, add userid and password strings. Click Add and type userid for the Name. Click Add again and type password for the NAME. __ g. Click Finish. __ h. Click OK. __ 10. The /Login Struts action will be called when the user clicks the Login button in the login.jsp. Add an Action Input from the /Login Struts Action to the login.jsp. This is in case the login information is not formatted correctly. For example, the password is empty or too short. __ a. Hover over the /Login Struts Action and drag the connection handle over to the login.jsp. __ b. Click login.jsp and select Action Input. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-15 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 16. Instructor Exercises Guide __ c. The Web Diagram should look as follows: __ 11. When the /Login Struts Action runs, the result may be success or failure. Add a local forward, representing success, from the /Login Struts Action to listitems.jsp. Add a local forward, representing failure, from the /Login Struts Action to error.jsp. __ a. Hover over the /Login Struts Action and drag the connection handle over to the listitems.jsp. Select Local Forward from the popup menu. A link named success will be added to the /Login Struts Action. __ b. Hover over the /Login Struts Action and drag the connection handle over to the error.jsp. Select Local Forward from the popup menu. A link named failure will be added to the /Login Struts Action. __ c. Save the Web diagram before continuing. 10-16 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 17. V4.1 Instructor Exercises Guide EXempty 10.5. Implement the JSP Pages Start by implementing the login.jsp and error.jsp Web pages. __ 12. Use Page Designer to implement the login.jsp page. __ a. In the diagram editor, double-click the login.jsp node. __ b. Switch the Page Designer to the Design tab. __ 13. The tool has added an <html:form> tag element with /Login as the action. As the message in the <div> indicates, cut the form from the <div> and paste it below. Add the page heading title to the login.jsp page, based on a string from the properties file. __ a. In the Outline view, drag the html:form element and drop it below the <body> tag. __ b. In the Outline view, right-click the <div> tag, below the html:form, and select Remove. __ 14. Add the page heading title to the login.jsp page, based on a string from the properties file. __ a. In Page Designer, click inside the form to select it. __ b. Select Format Paragraph Heading 1 from the main menu. __ c. In the Palette view, expand the Struts Bean Tags drawer and double-click the Message component. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-17 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 18. Instructor Exercises Guide __ d. In the Properties view, the bean:message tab should be automatically selected, type index.title as the Direct Key. Press ENTER to commit your changes. Verify that the text IBM Library System appears in the login.jsp file. Note Question marks will appear to the left of your title if Page Designer does not recognize the custom tag being inserted into the page. If this situation occurs, verify that the following custom tag prefix declarations appear in the source of the JSP file: 10-18 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 19. V4.1 Instructor Exercises Guide EXempty __ 15. Add a Struts error message section below the title heading. __ a. Position the cursor after the IBM Library System heading and press ENTER to move the cursor to the next line. __ b. Select Format Paragraph Normal from the main menu. __ c. In the Palette view, expand the Struts HTML Tags drawer, double-click the Errors component. A list of sample error messages should now appear in the Page Designer. __ 16. Add the user ID label, password label, and form fields to the JSP file. __ a. In Page Designer, click on the Errors component and press the down arrow key to move the cursor to the next line. __ b. In the Palette view, double-click the Message component in the Struts Bean Tags drawer. Type global.field.userid in the Properties view under Direct Key. __ c. Press the SPACE key to add a space after the Message component. __ d. Double-click the Message component in the Palette view again to insert another text label. This time type global.field.password in the Direct Key field under the bean:message tab in the Properties view. __ e. Position the cursor in between the two messages in Page Designer. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-19 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 20. Instructor Exercises Guide __ f. In the Palette view, double-click the Text component in the Struts HTML Tags drawer. __ g. In the Properties view, the html:text tab should be automatically selected, type userid in the Property field. __ h. In the Page Designer, press ENTER to move the Password label to the next line. __ i. Position the cursor after the Password label. You can do this by selecting the Password label and pressing the right arrow key. __ j. Double-click the Password component under the Struts HTML Tags drawer in the Palette view. In the Properties view, under the html:password tab, type password in the Property field. __ 17. Set the submit button to use a Struts Message component for the label. __ a. Select the Submit Query button. __ b. In the Palette view, double-click the Message component under Struts Bean Tags. 10-20 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 21. V4.1 Instructor Exercises Guide EXempty __ c. The button should now have Missing attribute(s): key name as the label. In the Outline view, select bean:message under the html:submit node. __ d. In the Property view, the Message tab appears. Type button.login in the Direct Key field. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-21 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 22. Instructor Exercises Guide __ e. The label on the button should change to Login. Note that if the label does not change, save your changes, close Page Designer and open it again. __ f. Save the changes. __ 18. Examine the Struts JSP tags in the login.jsp source view. __ a. Switch to the Source tab of the page designer. __ 19. Implement the error.jsp file. __ a. Switch to the Web Diagram editor and double-click the error.jsp node. __ b. In the Page Designer, click the Source tab. Add the following content in between the <body> </body> tags. Note that the content can be copied from <LAB_FILES>Strutssnippetssnippet02.txt. <h1><bean:message key="index.title"/></h1> <h2>Error Page</h2> <p> <html:errors/> <p> <a href="login.jsp"><b>Return to Login Page</b></a> 10-22 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 23. V4.1 Instructor Exercises Guide EXempty __ c. Click the Preview tab to see the results. __ d. Save and close error.jsp. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-23 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 24. Instructor Exercises Guide 10.6. Implement the Action Form Class Implement the action form that processes the user ID and password from the login JSP file. This Form Bean class contains a member instance field and accessor methods (getters and setters) for each field in the input form. It also provides simple field checking. Note The terms Struts form, action form, and form bean are synonymous. __ 20. Implement the validate method in the LoginForm.java action form class. __ a. Open the Web Diagram, double-click the LoginForm inside of the /Login Struts action. __ b. When the LoginForm was created, the wizard filled in most of the elements in the class. This included the two fields (userid and password) and their getters and setters. Scroll down in the file to the ActionErrors validate method and replace the method body with code found in <LAB_FILES>Strutssnippetssnippet03.txt. ActionErrors errors = new ActionErrors(); if ((getUserid() == null) || (getUserid().length() == 0)) { errors.add("userid", new ActionError("error.login.nouserid")); } else { try { Integer.parseInt(getUserid()); } catch (Exception e) { errors.add( "userid", new ActionError("error.login.nointuserid")); } } if ((getPassword() == null) || (getPassword().length() == 0)) { errors.add("password", new ActionError("error.login.nopassword")); } return errors; __ c. Use Source Organize Imports to fix any errors related to missing imports. When prompted, choose org.apache.struts.action.ActionError in the Organize Imports dialog. __ d. Save and close LoginForm.java. 10-24 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 25. V4.1 Instructor Exercises Guide EXempty 10.7. Implement Action Mapping and the Action Class The next step is to implement the /Login action mapping and the LoginAction class. The LoginAction class will be invoked with the data from the login form. This class can be used to implement the calls to business logic. It can also be used to make sure that the state and conditions are correct for invoking the business logic. In this exercise, it will be used to authenticate the user's ID and password. __ 21. Implement the execute method in the LoginAction class. __ a. Open the Web Diagram, double-click the /Login Struts Action node. __ b. In the Java editor for the LoginAction class, replace the execute method with the one found in <LAB_FILES>Strutssnippetssnippet04.txt. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionForward forward = new ActionForward(); HttpSession session = request.getSession(); LoginForm loginForm = (LoginForm) form; try { int id = Integer.parseInt(loginForm.getUserid()); String password = loginForm.getPassword(); Patron patron = Patron.findById(id); if (patron==null || !password.equals(patron.getPassword())) { errors.add( "login", new ActionError("error.login.failed") ); } ArrayList<LoanedCopy> items = new ArrayList<LoanedCopy>(); Collection copies = patron.getCopies(); Iterator copyIt = copies.iterator(); while (copyIt.hasNext()) { Copy copy = (Copy)copyIt.next(); Item item = copy.getItem(); LoanedCopy loanedCopy = new LoanedCopy(copy.getItemId(), copy.getCopyNumber(), item.getTitle(), item.getAuthor(), copy.getDue(), copy.getTimesRenewed()); items.add(loanedCopy); } session.setAttribute("PATRON", patron); © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-25 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 26. Instructor Exercises Guide session.setAttribute("itemList", items); } catch (Exception e) { errors.add( "login", new ActionError("error.login.exception") ); } if (!errors.isEmpty()) { saveErrors(request, errors); forward = mapping.findForward("failure"); } else { forward = mapping.findForward("success"); } return (forward); } __ c. Use Source Organize Imports to fix any errors that may come up. When prompted, choose: - java.util.Iterator - java.util.Collection - com.ibm.libary.model.Copy - com.ibm.libary.model.Item __ d. Save and close LoginAction.java. 10-26 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 27. V4.1 Instructor Exercises Guide EXempty 10.8. Test the Struts Pages At this point, you have implemented the login feature in the LibraryWeb application. Test this new feature by running the LibraryWeb application in the Integrated Test Environment. Since you have added the Library enterprise application to the server in a previous exercise, you only need to run the new login page on the server. __ 22. Test the user ID and password validation features in the Login action class. __ a. In the Project Explorer view, right-click LibraryWeb WebContent login.jsp and select Run As Run on Server. __ b. If the Run On Server dialog opens, click Finish. __ c. Once the login page loads in the browser, type abc in the User ID field, then click Login. __ d. You should be returned to the login page again, with two error messages showing at the top. __ 23. Test the failure navigation rule in the Login action class. __ a. Type 2 in User ID and password in Password, click Login. __ b. You should be forwarded to the error page, with a message noting that the User ID/Password pair is invalid. __ c. Click Return to Login Page to return. __ 24. Test the success navigation rule in the Login action class. __ a. This time in the login page, type 2 in User ID and vogel in Password. Click Login. © Copyright IBM Corp. 2004, 2007 Exercise 10. Create a Struts Application 10-27 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
  • 28. Instructor Exercises Guide __ b. You should now be successfully forwarded to the item list page and be able to make renew requests. End of exercise 10-28 Developing Web Applications © Copyright IBM Corp. 2004, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.