Refactoring: Move presentation logic from JSP page to Action and Tiles

October 12, 2005

Category: Techy

Tags: , ,

to

Motivation

To prevent too much logic from being placed in the JSP page directly which makes things harder to debug as it will be mixed in with other HTML. One other alternative is to create separate pages for each state. However, to reduce code duplication we can put all of the buttons on the same page just hide or show them as needed.

Mechanics

  1. Define state subgroupings on paper
  2. Define state groupings on paper
  3. Define additional local forwards based on the groupings in struts-config.xml
  4. Define extensions to the page in your tiles-config.xml
  5. Convert the single return mappings.findForward("page") to break it up into conditions that will send to the appropriate forward
  6. Define which sections should be shown and not shown in your tiles-config.xml
  7. If sub-tiles are used. Rename the tiles defintion for the subtile and make the original definition include the new subtile definition. This is to get around Tiles not passing in context data to its subtiles.
  8. Add <tiles:useattribute> for the attributes that define which sections can be seen to the JSP page.
  9. Replace the multiple logic sections with a single <logic:equals>
  10. Remove old forwards from struts-config.xml

Example

  1. For the example above there are three subgroups:
    • validity
    • status
    • access
  2. We then create the following pattern for the groupings: [pageName].[validity].[status].[admin] Examples of the pattern applied are:
    • summaryPage.valid.assigned.admin
    • summaryPage.invalid.assigned.admin
    • summaryPage.valid.assigned.user
    • summaryPage.valid.rejected.user
  3. We add the new forwards to struts-config.xml

  4. We add new tiles-config.xml definitions based on the first one:

  5. In our execute method, we replace

    with

  6. We add additional attributes to the tiles-config.xml

  7. Sub-tiles aren’t used in this situation, however if we are using sub-tiles like the following:

    Tiles will not render the following definition correctly or as one would normally expect.

    Since the tiles attributes are not passed across definitions. To get around this we need to create a separate tile for the view.

  8. In the beginning of the JSP file we put in the following tags

    Ignore is set to true so that in case it is not defined in the definition, it will still load the page. It is okay to have it present as well.

  9. We replace the deeply nested logic:equals such as

    with

  10. The last thing to do is remove the old forward from the struts-config.xml since it is no longer needed.