Chapter 4 Tutorials

Chapter 4 Tutorials

Enhanced

Before adding the features for Chapter 4, do the following.

  1. Use the NetBeans project that was created in the Chapter 1 Tutorials.
  2. Download the following JAR files from the book's web site.
    1. log4j
    2. commons collections
    3. commons logging
    4. commons beanutils
  3. Right-click the Libraries folder in the NetBeans project.
    1. Select Add Jar/Folder
    2. Navigate to the directory that contains the downloaded JAR files.
    3. Select all four JAR files and select Open.
  4. Open the Source Packages folder.
    1. Create a new package named shared.
      1. Create a new class named HelperBaseCh4.
        1. Copy the contents of the HelperBase file from the Chapter 3 tutorials.
        2. Change the name in all the appropriate places to HelperBaseCh4.
    2. Create a new package named ch4.enhanced.
      1. Copy the controller class and the controller helper class from the Reorganised tutorial for Chapter 3. Refactor as necessary.
  5. Create a visible folder named ch4/enhanced for the JSPs. Copy the JSPs from the reorganised controller from Chapter 3.

Adding a Logger

  1. Open the Source Packages folder.
    1. Create a new class named InitLog4j in the shared package. Copy the contents for it from the book's web site.
    2. Modify the HelperBaseCh4 file in the shared package.
      1. Add a member variable for a logger object of type org.apache.log4j.Logger.
      2. Create a helper method named initLogger.
        1. Read the initialization parameter that contains the name for the log file. Get the logger with that name.
        2. Read the initialization parameter that contains the level for the log file. Set the level of the logger to that level.
        3. Call the initLogger method from the helper base constructor.
  2. Modify ControllerHelper file.
    1. Extend it from shared.HelperBaseCh4.
    2. Add an info message to the following methods. Write a message like "Called method-name method" for each:
      1. ControllerHelper constructor.
      2. ControllerHelper doGet.
      3. HelperBase constructor.
      4. HelperBase initLogger.
  3. Edit the web.xml file.
    1. Add a servlet definition for the InitLog4j servlet.
      • Include an initialization parameter for the location of the log file. The name of the parameter should be logPath. Give it a value of /WEB-INF/logs/error.ch4.log
      • Add the load on startup tag.
    2. Add a servlet definition for the controller.
      • Include an initialization parameter named logName for the default name of the logger. Set the name as bytesizebook.guide.ch4
      • Include an initialization parameter named logLevel for the default level of the logger. Set the level as INFO
    3. Add a servlet mapping for the controller.
    4. Do not create servlet definitions or servlet mappings for any of the other files in the package.
  4. Modify the JSPs. Replace all EL statements that used the bean reference so that they now use the helper and the bean in the helper.
    1. Replace ${refData.hobby} with ${helper.data.hobby}. If you used a name other than helper to save the helper in the session, then use that name instead.
  5. Open the Web Pages folder.
    1. Open the WEB-INF folder.
    2. Create folder named logs.
    3. Open the logs folder.
    4. Create a file named error.ch4.log.
  6. Modify the index.jsp file.
    1. Modify the page by adding a hypertext link to the controller.
    2. Do not link to the edit page; all accesses should be to the controller.
  7. Run the project.
    1. The index.jsp page will appear in the browser.
    2. Enter data into each field.
    3. Access each page of the application and click each button on each page.
    4. Notice that the data is sent from page to page.
    5. Return to the edit page by clicking the edit button.
    6. Click in the location bar in the browser and press enter.
    7. You will see that the old data is still shown in the input elements, even though there is no data in the query string. That is because the data is being read from the session.
    8. In your browser, remove the cookie for the JSESSIONID.
    9. Click in the location bar in the browser and press enter.
    10. You will see that the data has dissappeared. The JSESSIONID cookie is what identifies the browser with the Tomcat session. When the cookie is gone, Tomcat cannot access the session.
    11. Click to the File tab in the NetBeans project.
      1. Open the build folder.
      2. Open the web folder.
      3. Open the WEB-INF folder.
      4. Open the logs folder.
      5. Open the error.ch4.log folder. You should see some messages there.
  8. Validate that all the JSP files contain valid HTML.
  9. Whenevere a log file is used. you will need to shut down Tomcat in NetBeans before doing a clean and build.
    1. Click the Services tab in the NetBeans project.
    2. Open the Servers folder.
    3. Right-click Apache Tomcat.
    4. Click Stop.
    5. Now you can do a clean and build.

Eliminating Hidden Fields

The copyFromSession and addHelperToSession methods are the keys to removing the hidden fields. The servlet can access data that was entered in the session during a previous request.

  1. Modify HelperBaseCh4 file.
    1. Change the class to an abstract class.
    2. Add an enumerated type named SessionData with the values READ and IGNORE.
    3. Add an abstract method named copyFromSession that has one parameter of type Object.
    4. Add a method named addHelperToSession that has two parameters of type String and type SessionData.
      1. If the session data parameter is READ, then try to read an object with the same name as the string parameter from the session. If the object is not null, then call copyFromSession with that object.
      2. Save the current object into the session using the name in the string parameter as the key.
  2. Modify ControllerHelper file.
    1. Implement the abstract method copyFromSession.
      1. Test if the parameter has the same type as the current object.
      2. If it does, then cast it to the same type and copy the data object from the session object into the data for the current object.
    2. Modify the doGet method.
      1. Replace the statement that adds the helper to the session with a call to the addHelperToSession method.
        1. Choose an appropriate name. This name will be used in the JSPs to access the controller helper.
        2. Set the session data to READ, so that the old data will be read from the session.
      2. The lines that copy the query string data into the bean must be moved. Move them into the if .. else block for the confirm button.
  3. Modify the JSPs.
    1. Remove all the hidden fields.
  4. Run the project.

Specifying the Location of JSPs

The jspLocation is used to define the path to the JSPs. It will be used to move the JSPs into the source package that contains the controller.

  1. Modify ControllerHelper file.
    1. Move the JSPs form the visible folder ch4/enhanced into the source package that contains the controller.
    2. Modify the doGet method.
      1. Add a method named jspLocation.
        1. The method returns a string.
        2. The method has a parameter that is a string.
        3. The method returns the full path to the JSPs concatenated with the string parameter. The path should be to the directory of the controller helper, since the JSPs have been copied there.
      2. Add a statement after the if .. else block, but before the request dispatcher statement, that modifies the address by calling the jspLocation method.

Automating the Controller Logic

The if .. else block of code can be removed from the controller. It will be replaced with a loop in the helper base. Methods will be used to handle each button that the user clicks.

  1. Add a class named ButtonMethod to the shared package. Copy the contents from the book's web site.
  2. Modify HelperBaseCh4 file.
    1. Add a member variable named methodDefault of type java.lang.reflect.Method.
    2. Copy the following methods from the online version of HelperBaseCh4.
      1. Copy the executeButtonMethod method that has no parameters. This method looks for the most derived class in a class heirarchy.
      2. Copy the executeButtonMethod method that has two parameters.
        1. This method searches through all the methods in the class, looking for the method with an associated button name.
        2. If no method is found in the class, then the super class is searched.
        3. If the method is found, then it is executed.
        4. After all super classes have been searched and no button name has been matched, then the default method is called.
      3. Copy the invokeButtonMethod method. This is the method that executes the method that was found for the button name in the query string.
      4. Copy the writeError method. This writes an error message to the browser if the button method cannot be executed.
      5. These methods refer to a logger named logger. If your logger has a different name, then replace all these occurences with the name of your logger.
      6. Add appropriate import statements.
  3. Modify ControllerHelper file.
    1. Modify the doGet method.
      1. Replace the nested if block with the single statement that assigns the return value of the executeButtonMethod to the address variable.
      2. Modify the address by calling jspLocation.
    2. Add a public method that returns a string for each button in the application.
      1. Annotate each method with the ButtonMethod annotation. Use the correct button name for each method.
      2. Set the method for the edit page as the default method. This corresponds to the final else in the old nested if block.
      3. In the method that corresponds to the confirm button, add the code that copies the query string data into the bean.

Automating Filling the Bean

Define the fillBeanFromRequest method and use it to automatically copy data from the query string into the bean.

  1. Modify HelperBaseCh4 file.
    1. Add a method named fillBeanFromRequest with one parameter of type Object.
      1. Try to call the populate method from the org.apache.commons.beanutils.BeanUtils class. Pass the object parameter and the parameter map from the request to the method.
      2. Catch the possible exceptions and write an appropriate message to your error log.
        1. IllegalAccessException
        2. java.lang.reflect.InvocationTargetException
  2. Modify the confirm method in the ControllerHelper.
    1. Remove the statements that copy the query string into the bean.
    2. Call the fillBeanFromRequest method.

Contact the author