©


J2EE Pattern Catalog | Design Considerations | Refactorings | Bad Practices | Resources



Core J2EE Pattern Catalog

© CoreJ2EEPatterns
All Rights Reserved.

Last Updated:
February 3, 2003 10:57 PM

 

 

Composite View

Context

Sophisticated Web pages present content from numerous data sources, using multiple subviews that comprise a single display page. Additionally, a variety of individuals with different skill sets contribute to the development and maintenance of these Web pages.

Problem

Instead of providing a mechanism to combine modular, atomic portions of a view into a composite whole, pages are built by embedding formatting code directly within each view.

Modification to the layout of multiple views is difficult and error prone, due to the duplication of code.

Forces

  • Atomic portions of view content change frequently.

  • Multiple composite views use similar subviews, such as a customer inventory table. These atomic portions are decorated with different surrounding template text, or they appear in a different location within the page.

  • Layout changes are more difficult to manage and code harder to maintain when subviews are directly embedded and duplicated in multiple views.

  • Embedding frequently changing portions of template text directly into views also potentially affects the availability and administration of the system. The server may need to be restarted before clients see the modifications or updates to these template components.

Solution

Use composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.

This solution provides for the creation of a composite view based on the inclusion and substitution of modular dynamic and static template fragments. It promotes the reuse of atomic portions of the view by encouraging modular design. It is appropriate to use a composite view to generate pages containing display components that may be combined in a variety of ways. This scenario occurs, for example, with portal sites that include numerous independent subviews, such as news feeds, weather information, and stock quotes on a single page. The layout of the page is managed and modified independent of the subview content.

Another benefit of this pattern is that Web designers can prototype the layout of a site, plugging static content into each of the template regions. As site development progresses, the actual content is substituted for these placeholders.

Figure 7.17 shows a screen capture of Sun's Java homepage, java.sun.com. Four regions are identified: Navigation, Search, Feature Story, and Headlines. While the content for each of these component subviews may originate from different data sources, they are laid out seamlessly to create a single composite page.

Figure 7.17
Figure 7.17 Screen shot of a modular page, including Search, Navigation, Feature Story, and Headlines regions

This pattern is not without its drawbacks. There is a runtime overhead associated with it, a tradeoff for the increased flexibility that it provides. Also, the use of a more sophisticated layout mechanism brings with it some manageability and development issues, since there are more artifacts to maintain and a level of implementation indirection to understand.

Structure

Figure 7.18 shows the class diagram that represents the Composite View pattern.

Figure 7.18
Figure 7.18 Composite View class diagram

Participants and Responsibilities

Figure 7.19 shows the sequence diagram for the Composite View pattern.

Figures 7.19
Figure 7.19 Composite View sequence diagram

Composite View

A composite view is a view that is an aggregate of multiple subviews.

View Manager

The View Manager manages the inclusion of portions of template fragments into the composite view. The View Manager may be part of a standard JSP runtime engine, in the form of the standard JSP include tag (<jsp:include>), or it may be encapsulated in a JavaBean helper (JSP 1.0+) or custom tag helper (JSP 1.1+) to provide more robust functionality.

A benefit of using a mechanism other than the standard include tag is that conditional inclusion is easily done. For example, certain template fragments may be included only if the user fulfills a particular role or certain system conditions are satisfied. Furthermore, using a helper component as a View Manager allows for more sophisticated control of the page structure as a whole, which is useful for creating reusable page layouts.

Included View

An included view is a subview that is one atomic piece of a larger whole view. This included view could also potentially be a composite, itself including multiple subviews.

Strategies

JSP View Strategy

See "JSP View Strategy" on page 190.

Servlet View Strategy

See "Servlet View Strategy" on page 191.

JavaBean View Management Strategy

View management is implemented using JavaBeans, as shown in Example 7.22. The view delegates to the JavaBean, which implements the custom logic to control view layout and composition. The decisions on page layout may be based on user roles or security policies, making it much more powerful than the standard JSP include functionality. While it is semantically equivalent to the Custom Tag View Management Strategy, it is not nearly as elegant, since it introduces scriptlet code into the view.

Using the JavaBean View Management Strategy requires less up-front work than using the preferred Custom Tag View Management Strategy, since it is easier to construct JavaBeans and integrate them into a JSP environment. Additionally, even novice developers understand JavaBeans. This strategy is also easier from a manageability standpoint, because the completed JavaBeans are the only resulting artifacts to manage and configure.

Example 7.22 JavaBean View Management Strategy

<%@page 
  import="corepatterns.compositeview.beanhelper.ContentHelper" %>

<% ContentHelper personalizer = new 
  ContentHelper(request); %>

    
<table valign="top" cellpadding="30%"  width="100%">
     <% if (personalizer.hasWorldNewsInterest() ) { %>
        <tr>
            <td><jsp:getProperty name="feeder" 
               property="worldNews"/></td>
        </tr>
        <%
        }
        if ( personalizer.hasCountryNewsInterest() ) {
        %>
        <tr>
            <td><jsp:getProperty name="feeder" 
               property="countryNews"/></td>
        </tr>
        <%
        }

        if ( personalizer.hasCustomNewsInterest() ) {
        %>
        <tr>
            <td><jsp:getProperty name="feeder" 
               property="customNews"/></td>
        </tr>
        <%
        }
        
        if ( personalizer.hasAstronomyInterest() ) {
        %>

        <tr>
            <td><jsp:getProperty name="feeder" 
                property="astronomyNews"/></td>
            </tr>
        <%
        }
        %>
    </table>

Standard Tag View Management Strategy

View management is implemented using standard JSP tags, such as the <jsp:include> tag. Using standard tags for managing the layout and composition of views is an easy strategy to implement, but does not provide the power and flexibility of the preferred Custom Tag View Management Strategy, since the layout for individual pages remains embedded within that page. Thus, while this strategy allows for the underlying content to vary dynamically, any site-wide layout changes would require individual modifications to numerous JSPs. This is shown in Example 7.23.

Example 7.23 Standard Tag View Management Strategy

<html>
<body>
<jsp:include 
  page="/jsp/CompositeView/javabean/banner.html" 
  flush="true"/> 
<table width="100%">
  <tr align="left" valign="middle">
    <td width="20%">
    <jsp:include 
    page="/jsp/CompositeView/javabean/ProfilePane.jsp" 
      flush="true"/> 
    </td>
    <td width="70%" align="center">
    <jsp:include 
      page="/jsp/CompositeView/javabean/mainpanel.jsp" 
      flush="true"/> 
    </td>
  </tr>
</table>
<jsp:include 
  page="/jsp/CompositeView/javabean/footer.html" 
    flush="true"/> 
</body>
</html>

When creating a composite display using standard tags, both static content, such as an HTML file, and dynamic content, such as a JSP, can be included. Additionally, the content can be included at translation time or at runtime. If the content is included at translation time, then the page display will remain unchanged until the JSP is recompiled, at which point any modifications to included content will be visible. In other words, the page is laid out and generated once, each time the JSP is recompiled. Example 7.24 shows an excerpt of a JSP that generates a composite page in this way, using the standard JSP include directive <%@ include %>, which includes content at translation time.

Runtime inclusion of content means that changes to underlying subviews are visible in the composite page the next time a client accesses the page. This is much more dynamic and can be accomplished using the standard JSP include tag <jsp:include>, as shown in Example 7.25. There is of course some runtime overhead associated with this type of view generation, but it is the tradeoff for the increased flexibility of on-the-fly content modifications.

Example 7.24 Composite View with Translation-Time Content Inclusion

<table border=1 valign="top" cellpadding="2%"  
    width="100%">
    <tr>
       <td><%@ file="news/worldnews.html" %> </td>
    </tr>
    <tr>
       <td><%@ file="news/countrynews.html" %> </td>
    </tr>
    <tr>
       <td><%@ file="news/customnews.html" %> </td>
    </tr>
    <tr>
       <td><%@ file="news/astronomy.html" %> </td>
    </tr>
</table>


Example 7.25 Composite View with Runtime Content Inclusion

<table border=1 valign="top" cellpadding="2%" 
  width="100%">
    <tr>
        <td><jsp:include page="news/worldnews.jsp" 
            flush="true"/> </td>
    </tr>
    <tr>
        <td><jsp:include page="news/countrynews.jsp" 
            flush="true"/> </td>
    </tr>
    <tr>
        <td><jsp:include page="news/customnews.jsp" 
            flush="true"/> </td>
    </tr>
    <tr>
        <td><jsp:include page="news/astronomy.jsp" 
            flush="true"/> </td>
    </tr>
</table>

Custom Tag View Management Strategy

View management is implemented using custom tags (JSP 1.1+), which is the preferred strategy. Logic implemented within the tag controls view layout and composition. These tags are much more powerful and flexible than the standard JSP include tag, but also require a higher level of effort. Custom actions can base page layout and composition on such things as user roles or security policies.

Using this strategy requires more upfront work than do the other view management strategies, since custom tag development is more complicated than simply using JavaBeans or standard tags. Not only is there more complexity in the development process, but there is much more complexity with respect to integrating and managing the completed tags. Using this strategy requires the generation of numerous artifacts, including the tag itself, a tag library descriptor, configuration files, and configuring the environment with these artifacts.

The following JSP excerpt shows a possible implementation of this strategy and is excerpted from Example 7.26. Please refer to that code sample for more detail.

<region:render 
    template='/jsp/CompositeView/templates/portal.jsp'>

<region:put section='banner' 
    content='/jsp/CompositeView/templates/banner.jsp' />

<region:put section='controlpanel' content=
    '/jsp/CompositeView/templates/ProfilePane.jsp' />

<region:put section='mainpanel' content=
    '/jsp/CompositeView/templates/mainpanel.jsp' />

<region:put section='footer' content=
    '/jsp/CompositeView/templates/footer.jsp' />
</region:render>

Transformer View Management Strategy

View management is implemented using an XSL Transformer. This strategy would typically be combined with the Custom Tag View Management Strategy, using custom tags to implement and delegate to the appropriate components. Using this strategy can help to enforce the separation of the model from the view, since much of the view markup must be factored into a separate stylesheet. At the same time, it involves technologies that require new and sophisticated skill sets to implement correctly, an issue that makes this strategy impractical in many environments where these technologies are not already established.

The following excerpt shows the use of a custom tag from within a JSP to convert a model using a stylesheet and transformer:

<xsl:transform model="portfolioHelper"
   stylesheet="/transform/styles/generalPortfolio.xsl"/>

Early-Binding Resource Strategy

This is another name for translation-time content inclusion, as described in the Standard Tag View Management Strategy and shown in Example 7.24. It is appropriate for maintaining and updating a relatively static template and is recommended if a view includes headers and footers that change infrequently.

Late-Binding Resource Strategy

This is another name for runtime-content inclusion, as described in the Standard Tag View Management Strategy and shown in Example 7.25. It is appropriate for composite pages that may change frequently. One note: If the subview included at runtime is a dynamic resource, such as a JSP, then this subview may also be a composite view, including more runtime content. The flexibility offered by such nested composite structures should be weighed against their runtime overhead and considered in light of specific project requirements.

Consequences

  • Improves Modularity and Reuse
    The pattern promotes modular design. It is possible to reuse atomic portions of a template, such as a table of stock quotes, in numerous views and to decorate these reused portions with different information. This pattern permits the table to be moved into its own module and simply included where necessary. This type of dynamic layout and composition reduces duplication, fosters reuse, and improves maintainability.

  • Enhances Flexibility
    A sophisticated implementation may conditionally include view template fragments based on runtime decisions, such as user role or security policy.

  • Enhances Maintainability and Manageability
    It is much more efficient to manage changes to portions of a template when the template is not hardcoded directly into the view markup. When kept separate from the view, it is possible to modify modular portions of template content independent of the template layout. Additionally, these changes are available to the client immediately, depending on the implementation strategy. Modifications to the layout of a page are more easily managed as well, since changes are centralized.

  • Reduces Manageability
    Aggregating atomic pieces of the display together to create a single view introduces the potential for display errors, since subviews are page fragments. This is a limitation that can become a manageability issue. For example, if a JSP page is generating an HTML page using a main page that includes three subviews, and the subviews each include the HTML open and close tag (that is, <HTML> and </HTML>), then the composed page will be invalid. Thus, it is important when using this pattern to be aware that subviews must not be complete views. Tag usage must be accounted for quite strictly in order to create valid composite views, and this can become a manageability issue.

  • Performance Impact
    Generating a display that includes numerous subviews may slow performance. Runtime inclusion of subviews will result in a delay each time the page is served to the client. In an environment with strict Service Level Agreements that mandate specific response times, such performance slowdowns, though typically extremely minimal, may not be acceptable. An alternative is to move the subview inclusion to translation time, though this limits the subview to changing when the page is retranslated.

Sample Code

The Composite View pattern can be implemented using any number of strategies, but one of the more popular is the Custom Tag View Management Strategy. In fact, there are a number of custom tag libraries currently available for implementing composite views that separate view layout from view content and provide for modular and pluggable template subviews.

This sample will use a template library written by David Geary and featured in detail in "Advanced JavaServer Pages" [Geary].

The template library describes three basic components: sections, regions, and templates.

  • A section is a reusable component that renders HTML or JSP.

  • A region describes content by defining sections.

  • A template controls the layout of regions and sections in a rendered page.

A region can be defined and rendered as shown in Example 7.26.

Example 7.26 A Region and Sections

<region:render template='portal.jsp'>
  <region:put section='banner' content = 'banner.jsp' />
  <region:put section = 'controlpanel' content = 
      'ProfilePane.jsp' />
  <region:put section='mainpanel' content = 
      'mainpanel.jsp' />
  <region:put section='footer' content='footer.jsp' />
</region:render>

A region defines its content by matching logical section names with a portion of content, such as banner.jsp.

The layout for the region and its sections is defined by a template, to which each region is associated. In this case, the template is named portal.jsp, as defined in Example 7.27.

Example 7.27 Template Definition

<region:render section='banner'/>
<table width="100%">
    <tr align="left" valign="middle">
        <td width="20%">
      <!-- menu region -->
      <region:render section='controlpanel' />
        </td>
        <td width="70%" align="center">
      <!-- contents -->
      <region:render section='mainpanel' />
        </td>
    </tr>
</table>

A site with numerous views and a single consistent layout has one JSP containing code that looks similar to the template definition in Example 7.27, and many JSPs that look similar to Example 7.26, defining alternate regions and sections.

Sections are JSP fragments that are used as subviews to build a composite whole as defined by a template. The banner.jsp section is shown in Example 7.28.

Example 7.28 Section Subview - banner.jsp

<table width="100%" bgcolor="#C0C0C0">
<tr align="left" valign="middle">
  <td width="100%">

  <TABLE ALIGN="left" BORDER=1 WIDTH="100%">
  <TR ALIGN="left" VALIGN="middle">
    <TD>Logo</TD>
    <TD><center>Sun Java Center</TD>
  </TR>
  </TABLE>

  </td>
</tr>
</table>

Composite views are a modular, flexible and extensible way to build JSP views for your J2EE application.

Related Patterns

  • View Helper
    The Composite View pattern may be used as the view in the View Helper pattern.

  • Composite [GoF]The Composite View pattern is based on the Composite pattern, which describes part-whole hierarchies where a composite object is comprised of numerous pieces, all of which are treated as logically equivalent.

  © 2001, Core J2EE Patterns, All Rights Reserved.