You are on page 1of 13

June 2005

Web Presentation Design Patterns for J2EE/.NET

By Ravi Sharda

The Web presentation layer of an application is responsible for what users see in the
user interface. Mechanisms like Java Servlet, Java Server Pages (JSP), ASP.NET,
etc., allow Web presentation layers to interface markup code (HTML, XML, etc.) with
server-side applications. This enables the application to serve users with interactive
pages and dynamic content.
Applications that have a fairly complex backend business logic face some design
challenges in terms of navigation and view management, separating different logical
layers, dynamic data models etc. This article shares knowledge gathered by the
author while evaluating the different design patterns that can be used to model the
presentation framework, for a project he worked on earlier.

Many online articles and technical white papers explain design patterns relating to
Web presentation and target a specific application platform. But how do you chose
the right design patterns for use in your Web application and how do you justify
using them?
This article introduces a few popular Web presentation design patterns that are used
both in the .Net and J2EE environment. The article further details the advantages
and disadvantages of the different design patterns and provides guidelines in
choosing the right pattern for a given application.
This article does not explain all the Design Patterns in use in the presentation layer,
but focuses on a few, most popular patterns. The article does not provide detailed
implementation strategies for using the Design Patterns. For such information, see
the Reference section at the end of the article.

This article is aimed at readers who are familiar with the presentation tier and the
common problems facing the presentation tier.

Key Terms
§ View – View is the combination of presentation code and presentation logic. View
code is typically HTML, JSP or ASP code. The terms view and presentation are
used interchangeably by many authors.
§ Model – The model represents the object model of the business or domain the
application addresses, it includes both data and behavior [1]. This is also referred
to as Domain Model or Business Model.
§ Presentation logic – This represents the display logic of the Domain Model. For
example, if the total revenue from a party exceeds $5 million, color the row for
the party, green.
§ Business logic – This represents the core application logic. It is also referred to as
Domain Logic [2].
§ Data access logic – Data access logic is the logic used for extracting information
from a data repository such as a relational database or an Enterprise Resource
Planning system.

Page: 1
Design Patterns
This article details the following popular design patterns that can be implemented in
some form or other under both Microsoft and Java platforms.
§ Model-View-Controller
§ Front Controller
§ Page Controller
§ View Helper
§ Intercepting Filter
The explanation for each of the patterns is organized as follows:
§ Problem – The problem that the pattern solves.

§ Context - The context of the problem and solution.


§ Solution – Explanation of the pattern’s solution to the problem
§ Advantages – The advantages of using the pattern.

§ Disadvantages – The disadvantages of using the pattern.

§ Applications that qualify for this pattern – Applications where the pattern is
best applied.

Model-View-Controller

Problem:

Applications that contain a mixture of view code, business logic code and data access
code, are difficult to maintain. A change in one place affects the entire application.
Due to high coupling, classes cannot be reused as they depend on other classes. To
add new data views, the application developer needs to copy the business logic,
which then requires maintenance in multiple places.
How do we decouple data access logic, business logic, data presentation, and user
interaction?

Context:

Usually, view changes more frequently than business logic and the model. Moreover,
they usually change at different times, as the drivers for change are different.
Designing visually appealing and interactive presentation requires a different skill set
than does developing complex business logic. Separating concerns is therefore very
useful as people with different skills can work on different components and then help
them integrate with the other components.
View code is more device-dependent than the business logic. If we want to migrate
the application from a browser-based application to support cell-phones, etc., we
must replace much of the view code, while the business logic remains unaffected.

Page: 2
Solution:

The Model-View-Controller (MVC) pattern separates the core Domain Model from the
view and the actions based on user inputs into three distinct layers as depicted in the
following figure:

<<bind>>
:Controller

<<updates>>
:Model

<<depends>>

:View

Figure 1 Model-View-Controller Structure

The three layers are as follows:


§ Model – The Model represents the business data and the business rules that
govern access to and updates of this data.
§ View – The view manages the display of the contents of a Model. It accesses the
business data through the Model and renders them in the display.

Template View and Transform View are two strategies of implementing views.
Several literatures available on the Web describe how to implement these.
§ Controller – The controller translates interactions with the view into actions to be
performed by the model. For example, it responds to the mouse or keyboard
input or GET and POST HTTP requests, and commands the model to change.
Controllers can be implemented using several design patterns, such as Front
Controller, Page Controller and Application Controller. The former two are
described in this article.
From figure 1, note that both the view and the controller depend on the model. The
model doesn’t depend on the controller or the view. Thus the model can be built and
tested independently of the view.
In the Java World, the Struts, a Jakarta project, provides a framework for
implementing the MVC pattern. The Struts architecture is derived from a combination
of The Front Controller and Intercepting Filter patterns, explained later in this article.
It provides a central controller servlet. The developer implements the model using
the Action Class to invoke business logic and Form Bean to encapsulate domain
model. The view is implemented in the JSP page.

Page: 3
ASP.NET implements the MVC pattern using the Page Controller pattern. In contrast
to the Struts implementation, which allows application-level control, the default
ASP.NET implementation applies the controller at the level of individual pages. The
data tier (such as .NET Datasets) represents the model. A developer implements the
view by developing the UI as an aspx page. The controller functions are implemented
in the code-behind file. More robust implementation of the MVC pattern can be
realized by using the Front Controller pattern.

Advantages:

§ Separation of Concerns. According to Martin Fowler [3], the pattern does two
separations in the presentation-tier. The first and the most important one is
separating the model from the view/controller. The second one is separating the
view and controller. This helps developers having different skill sets, in
developing different components and then helping the components to integrate.
§ Supports multiple views. Multiple views of the same data can be presented, using
the same model. For example, the same model data can be displayed as pie
chart, bar graph, or a spreadsheet.
§ Supports new types of clients. To support new types of clients one simply needs
to code a view and some controller logic and wire them into the existing
application. For example, the Web and Mobile interface for a banking application
can use the same model.
§ Easier maintenance. Changes affecting only the view become easier to make.
Moreover, as multiple views and multiple types of clients can use the same
model, this leads to easier maintenance due to code re-use.
§ Easier testing. The domain model and the business logic is encapsulated by the
model and is therefore easier to test.

Disadvantages:

§ Increased design complexity. The pattern introduces new classes or modules due
to the separation of model, view and controller. Moreover, various auxiliary
patterns, such as Front Controller and Intercepting Filter, may co-occur with
MVC, adding to the complexity.

§ Close coupling. Changes to the model interface require changes in the view and
in some cases in the controller as well. This poses problems when the model
changes frequently.

Applications that qualify for this pattern:

This pattern is very useful for a complex application where strict separation of view
and business layers would improve maintainability and testability of the application.
It is also useful in an application where multiple views of the application use the
same model.

Page: 4
Front Controller
Problem:

Most applications require a centralized access point for presentation-tier request


handling, to support the integration of system services (authentication and
authorization), content retrieval, view management, and navigation. If no such
central point is used, the following problems may occur:
§ Each view is required to implement its own system services which implies
replicated code

§ View navigation is handled by the view which may result in a mixture of view
logic and navigation

How do we provide a centralized access-point for presentation-tier request handling?

Context:

The presentation-tier request handling mechanism must control and coordinate


processing of each user across multiple requests. Such control mechanisms may be
managed in either a centralized or decentralized manner.
Common system services such as authentication and authorization checks are used
per request.

Solution:

This pattern directs all request handling through a single controller. A Front
Controller usually consists of a request handler and a command component,
comprising of the command interface and a hierarchy of commands. The following
figure depicts the class diagram of a Front Controller.

Figure 2 Front Controller class diagram

The handler receives the request from the Web server. It retrieves relevant
parameters from the request and uses them to dispatch the request to the right
command for processing. After the command object completes the action, it chooses
the view to render the page.
The handler invokes common functionality such as system services before
dispatching to the command. The command component may handle view
management and navigation based on settings defined in a configuration file.

Page: 5
Advantages:

§ Centralizes control. A central controller provides the means to handle common


functionality at a central place across multiple requests. This improves
maintainability of the system as code related to common functionality is reused
and is located at a central place.
§ Improves Security Manageability. Illicit access attempts are easier to trace using
the single access point.
§ Dynamic invocation of commands. The command to handle the request is
dynamically determined based on the request. Thus new commands can be
added and tested dynamically.

Disadvantages:

§ Single point of failure. Due to the single place for controlling all requests, it is
possible to introduce a single point of failure. This can be solved using multiple
controllers in the same server or in a cluster.

§ Increased complexity. Simpler applications may not need centralized control or


view navigation. The front controller adds additional classes that may make the
application more complex.

§ Performance. As many different requests pass through the Front Controller, it


may be performance sensitive. Placing logic in the Front Controller which is not
used for all requests adds unnecessary overhead to some requests [4].
§ Use of .NET Services. Implementing a Front Controller infrastructure in ASP.NET
prevents developers from using Server Side controls, ViewState and other
services. This is because of the Post back functionality, due to which .NET takes
control of the Form action [5].

Applications that qualify for this pattern:

This pattern can be used in an application where one needs to enforce common
behavior across multiple pages.

This pattern can also be applied in an application that needs to determine the
navigation between pages based on flexible configuration.

Page Controller

Problem:

Scripted server pages such as ASP.NET and JSP enable developers to create dynamic
pages with little effort, by allowing code blocks (scripts/scriptlets) and static HTML to
coexist. However, they also allow developers to easily create poorly designed all-
encompassing pages. One example of a poorly designed page is one that displays a
form, validates the inputs, processes the business data, and confirms the updates.
Creating all-encompassing pages might be easy and convenient, but maintenance is
a nightmare. Changes in the presentation logic may introduce defects in the business
logic and vice versa. Testing the business logic independently is difficult. Moreover,
the business logic cannot be reused.
How do you separate business logic and controller logic from the presentation-tier?

Page: 6
Context:

In dynamic Web applications, different user actions can lead to different controller
logic, followed by the same view. For example, in an application displaying data,
both updating and creating data from the user interface may lead the user to the
same refreshed page, even though different actions were performed.
As mentioned earlier, the presentation-tier request handling mechanism can control
and coordinate processing of each user across multiple requests, either in a
centralized (for example, using a Front-Controller) or a decentralized manner (for
example, using a Page-Controller).

Separating view and presentation logic from the controller and business logic makes
it easier to test the business logic and improves the maintainability of the system.
Since the drivers for change in business logic and presentation logic are different,
they are usually changed at different times. Thus, clear separation of these reduces
the chance of changes in one introducing defects in the other.

Solution:

The Page Controller pattern uses one input controller (Page Controller) for each
logical page. The controller is usually a separate object that corresponds to the page
or a separate page containing controller logic. It accepts input from the Web server
request, invokes the requested actions on the model, and calls the view. The
mechanism mirrors how static HTML pages are handled.

Figure 3 Page Controller class diagram

This is the default pattern used by ASP.NET or JSP. A single file handles the request
for a specific page. Encapsulating application logic and view code in one logical file
provides poor separation of logic. ASP.NET supports a concept called “Code-Behind”,
which is an object for each logical page and is used to separate out the application
logic from the view code. In Java the same effect can be achieved by using a servlet
as a Page Controller and using the “forward” method of “RequestDispatcher” to pass
control from the controller to the JSP.
Creating a controller for each page can lead to significant code duplication if common
behavior exists such as using system services, session management, etc. A solution
to this problem is using a base controller class to incorporate common functions.
Additionally, one can define a set of helper classes that the controllers use to
perform common functions.

Page: 7
Advantages:

§ Separation of concerns. The developer of the Page Controller can focus on the
model as well as business logic while the page developer can focus on the page
presentation.
§ Testability and Maintainability. The model and the business logic can be
independently tested. Due to separation of logic, the system is easier to
maintain. Chances of introducing defects when changing the presentation or the
business logic are greatly reduced.
§ Simplicity. Since each page has its own controller, the controller can itself remain
simple.

Disadvantages:

§ Large number of controllers. Using the Page Controller pattern in a large Web
application may lead to a large number of Page Controllers. A small common
change across all pages may require you to change all of these controllers.

§ Duplicate code. Each Page Controller must provide its own system services,
resulting in duplicate code. A small change in invoking system services
necessitates changes in all of the controllers.

§ Complex inheritance hierarchies. Using inheritance to implement common


behavior can lead to complex inheritance hierarchies in a large application. Due
to page variations, one may need to add additional levels in the inheritance
hierarchy. This may lead to problems in maintaining the application, as small
changes in one level may introduce defects in the others.
§ Fixed navigation. Large applications often require dynamic configuration of pages
and navigation among pages. Since navigation is hard-coded into the controllers,
the application may become hard to maintain as it grows large.

Applications that qualify for this pattern:

This pattern can be used in an application where a single component has the dual
responsibilities of application logic and display, as application logic can be separated
out in objects, as mentioned earlier in the section.

Moreover, it is used in applications that do not have dynamic navigation structures.


Note: As mentioned earlier, common functions can be separated out in a base
controller class. When the base controller class begins to have special case logic in
its types of requests, it may be a good idea using a Front Controller instead [6].

View Helper

Problem:

The Presentation tier changes often and are difficult to maintain when business logic
and domain model are interwoven with view code. This also reduces modularity and
testability and leads to poor separation of concerns among developers proficient in
business logic and presentation.

Page: 8
How do you separate logic not related to presentation formatting from the
presentation tier in order to maximize code reuse, maintainability and testability of
the system?

Context:

View code intermingled with application logic is usually difficult to maintain, as view
code changes more often than application logic. This also leads to poor separation of
roles, as developers with different skill set need to work on the same components.

Multiple views may display data extracted from the domain model in different ways.

Solution:

This pattern suggests encapsulating logic not related to presentation formatting,


such as business logic, in helper classes instead of the view. Logic not related to
presentation formatting includes validation, content retrieval initiating logic, adapting
or formatting the model, etc. Helper classes may delegate to business services. The
view then only consists of presentation code and delegates all processing
responsibilities to its helper classes.

Figure 4 View Helper class diagram

One way to implement this pattern in Java is to use JSP as the view and Java
classes, JavaBeans or custom tags as its helper classes. In .NET, an ASP page may
serve as the view and custom ASP controls or custom .NET classes may serve as
helper classes.

Advantages:

§ Improves code modularity. Since the business logic is encapsulated in View


Helpers, the application becomes more modular and aids reuse.

§ Aids code reuse. Multiple views may use the same helpers to display model data
in different ways.
§ Improves maintenance. The pattern helps in reducing the script code in the
presentation, as most of the scripted code may be encapsulated in View Helpers.
§ Separation of Concerns. Business logic developers can encapsulate business logic
is in View Helpers, while Web developers can work on the view code.

Disadvantages:

§ Increased complexity. Since code is partitioned into View Helpers, the application
becomes more complex. But this is usually offset by the improved maintainability
and code reuse.

Applications that qualify for this pattern:

This pattern is useful in applications where clean separation of roles among


developers of business logic and view code is required.

Page: 9
It is also useful in applications where the view changes frequently, which leads to
maintenance problems due to copy-and-paste of business logic.
The pattern is also useful in applications where multiple views use the same business
logic or domain model.

Intercepting Filter
Problem:

Web requests and responses often require preprocessing and post-processing steps.
For example, a Web request may require to be passed through a series of pre-
processing services:

§ Is the client authenticated and is part of a valid session?


§ Has the request originated from a trusted network?

§ Is the client’s browser type supported?

§ What is the client’s encoding scheme for sending data?

How do we implement common pre-processing and post-processing services during a


Web page request?

Context:

Conditional checks may be used in the application logic to conduct pre-processing


and post-processing services, but using them leads to code-fragility.
Pre-processing and post-processing logic, such as detecting data encoding schemes,
dealing with HTTP headers, Web session management, etc., should be separated
from application logic, to enable one to reuse the application logic easily in
environments not using a Web client.

Typically, pre-processing and post-processing logic change at a much slower pace


than application logic. For example, the code for detecting the data encoding scheme
for the client is not likely to change for every change in the application logic.
Typically, the pre-processing and post-processing services are independent of each
other and should be encapsulated into independent components for maximum reuse.
This also aids in adding or removing components without affecting existing
components, so that these components can be used in a variety of combinations.
As pre-processing and post-processing services are performed for each request or
response, the functions they perform need to be small and efficient.

Solution:

The Intercepting Filter intercepts and applies filters to incoming requests and
outgoing responses. The pattern suggests creating pluggable and independent filters
to process common pre-processing and post-processing services, which can be
added or removed in a declarative manner. This allows them to be applied in a
variety of combinations, without requiring changes to the application logic.

Page: 10
A simple strategy for implementing the Intercepting Filter pattern is creating a filter
chain that iterates through a list of filters. The Web request handler executes the
filter chain before passing control to the application logic.

Target resource.

Client RequestHandler Controller

FilterChain «interface»
Filter

Filter1 Filter2

Figure 5 Intercepting Filter class diagram

The Web request handler in the Web Server receives the request and passes control
to the Filter Chain. The Filter Chain iterates through a list of all filters configured in a
configuration file and executes each filter through a generic interface. After all filters
have been executed, the Request Handler passes control to the controller, which is
the target resource and contains the application logic. The filters can also manipulate
the request or response, for example by adding information in the request.

Advantages:

§ Separation of concerns. Since pre-processing and post-processing services are


encapsulated into separate filters, these can be constructed by developers expert
in the particular area. Moreover, since application logic is separated out from
these functions, the application logic code is not affected by changes in these
functions, and vice versa.
§ Centralizes Control. Filters provide a common place for handling pre-processing
and post-processing services across multiple requests.
§ Re-use. Well-designed filters can be transparently added or removed from
existing code, and can work in various combinations. These can be easily reused
in multiple applications.
§ Flexible Configuration. Filter chains are constructed based on a configuration file
and therefore can be easily changed. Moreover, the code base need not be
recompiled when the configuration is changed.

Page: 11
Disadvantages:

§ Information sharing. Filters do not provide explicit means for exchanging


information among them. Filters can share information, for example, by
massaging information in the request or response, but this is inefficient.
§ Performance. Since filters are executed for each request or response, they must
be efficient.

§ Filter execution order. By definition filters are loosely coupled and can be used in
various combinations. Therefore, no filter can make assumptions about other
filters.

Applications that qualify for this pattern:

This pattern can be used in applications where common pre-processing and post-
processing services need to be performed before incoming requests are received or
before outgoing responses are sent.
Note: The pattern centralizes common functionality across multiple requests, like the
controller. The following points summarize the different usage scenarios handled by
them:
§ Filters are better suited to massaging requests and responses for eventual
handling by a target resource, such as controller while controllers are better
suited to handling common application logic such as authentication, logging,
encryption, etc. at a central place.
§ Filters allows for loosely coupled, independent handlers which can be used in
various combinations while controllers often tie together management of
unrelated common services.

Typically, the processing logic inside a filter is not dependent on the state of the
application. This may not be the case for a controller.

Conclusion
This article describes popular design patterns used in applications having Web
presentations, namely: Model-view-Controller, Front Controller, Page Controller,
View Helper and Intercepting Filter patterns. The article presents the advantages and
disadvantages of the design patterns and provides guidelines on choosing the right
patterns based on the application characteristics.

Reference
1. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley
Pub Co, ISBN – 0321127420
2. Core J2EE Patterns
http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
3. Organizing Presentation Logic
http://martinfowler.com/eaaDev/OrganizingPresentations.html
4. Front Controller
http://wact.sourceforge.net/index.php/FrontController?PHPSESSID=8274c873b3
62595d0de1c35163316386

Page: 12
5. http://weblogs.asp.net/ngur/articles/168365.aspx

6. Model View Controller


http://wact.sourceforge.net/index.php/ModelViewController
7. OnJava.com J2EE Design Patterns
http://www.onjava.com/pub/a/onjava/2002/01/16/patterns.html

8. J2EE Patterns Catalog http://java.sun.com/blueprints/patterns/catalog.html


9. Web Presentation Patterns
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/dnpatterns/html/EspWebPresentationPatterns.asp
10. Migrating to Page Controllers
http://www.onlamp.com/pub/a/php/2004/10/14/page_controller.html
11. Catalog of Patterns of Enterprise Application Architecture
http://www.martinfowler.com/eaaCatalog/index.html
12. Page Controller
http://wact.sourceforge.net/index.php/PageController?PHPSESSID=8274c873b36
2595d0de1c35163316386

Ravi Sharda works for Qwest Software Services (QSS), Bangalore and is part of the QCC-CLEC team. He
worked in the Media & Broadcasting domain before joining Qwest. At QSS he works on Telecom
Operations Support Systems/Business Support Systems (OSS/BSS). He has a Master’s degree in
Engineering Management from the University of Missouri-Rolla, MO, USA and a Bachelor’s degree in
Mechanical Engineering from Indian Institute of Technology, Roorkee, India.

Page: 13

You might also like