Model View Controller
Splits user interface interaction into three distinct roles.
Model View Controller ( MVC ) is one of the most quoted (and most misquoted) patterns around. It started as a framework developed by Trygve Reenskaug for the Smalltalk platform in the late 1970s. Since then it has played an influential role in most UI frameworks and in the thinking about UI design.
How It Works
MVC considers three roles. The model is an object that represents some information about the domain. It’s a nonvisual object containing all the data and behavior other than that used for the UI. In its most pure OO form the model is an object within a Domain Model ( 116 ). You might also think of a Transaction Script ( 110 ) as the model providing that it contains no UI machinery. Such a definition stretches the notion of model, but fits the role breakdown of MVC.
The view represents the display of the model in the UI. Thus, if our model is a customer object our view might be a frame full of UI widgets or an HTML page rendered with information from the model. The view is only about display of information; any changes to the information are handled by the third member of the MVC trinity: the controller. The controller takes user input, manipulates the model, and causes the view to update appropriately. In this way UI is a combination of the view and the controller.
As I think about MVC I see two principal separations: separating the presentation from the model and separating the controller from the view.
Of these the separation of presentation from model is one of the most fundamental heuristics of good software design. This separation is important for several reasons.
• Fundamentally presentation and model are about different concerns. When you’re developing a view you’re thinking about the mechanisms of UI and how to lay out a good user interface. When you’re working with a model you are thinking about business policies, perhaps database interactions. Certainly you will use different very different libraries when working with one or the other. Often people prefer one area to another and they specialize in one side of the line.
• Depending on context, users want to see the same basic model information in different ways. Separating presentation and view allows you to develop multiple presentations—indeed, entirely different interfaces—and yet use the same model code. Most noticeably this could be providing the same model with a rich client, a Web browser, a remote API, and a command-line interface. Even within a single Web interface you might have different customer pages at different points in an application.
• Nonvisual objects are usually easier to test than visual ones. Separating presentation and model allows you to test all the domain logic easily without resorting to things like awkward GUI scripting tools.
A key point in this separation is the direction of the dependencies: the presentation depends on the model but the model doesn’t depend on the presentation. People programming in the model should be entirely unaware of what presentation is being used, which both simplifies their task and makes it easier to add new presentations later on. It also means that presentation changes can be made freely without altering the model.
This principle introduces a common issue. With a rich-client interface of multiple windows it’s likely that there will be several presentations of a model on a screen at once. If a user makes a change to the model from one presentation, the others need to change as well. To do this without creating a dependency you usually need an implementation of the Observer pattern [ Gang of Four ], such as event propagation or a listener. The presentation acts as the observer of the model: whenever the model changes it sends out an event and the presentations refresh the information.
The second division, the separation of view and controller, is less important. Indeed, the irony is that almost every version of Smalltalk didn’t actually make a view/controller separation. The classic example of why you’d want to separate them is to support editable and noneditable behavior, which you can do with one view and two controllers for the two cases, where the controllers are strategies [ Gang of Four ] for the view. In practice most systems have only one controller per view, however, so this separation is usually not done. It has come back into vogue with Web interfaces where it becomes useful for separating the controller and view again.
The fact that most GUI frameworks combine view and controller has led to many misquotations of MVC. The model and the view are obvious, but where’s the controller? The common idea is that it sits between the model and the view, as in the Application Controller ( 379 ) —it doesn’t help that the word “controller” is used in both contexts. Whatever the merits of a Application Controller ( 379 ), it’s a very different beast from an MVC controller.
For the purposes of this set of patterns these principles are really all you need to know. If you want to dig deeper into MVC the best available reference is [ POSA ].
When to Use It
As I said, the value of MVC lies in its two separations. Of these the separation of presentation and model is one of the most important design principles in software, and the only time you shouldn’t follow it is in very simple systems where the model has no real behavior in it anyway. As soon as you get some nonvisual logic you should apply the separation. Unfortunately, a lot of UI frameworks make it difficult, and those that don’t are often taught without a separation.
The separation of view and controller is less important, so I’d only recommend doing it when it is really helpful. For rich-client systems, that ends up being hardly ever, although it’s common in Web front ends where the controller is separated out. Most of the patterns on Web design here are based on that principle.
Page Controller
An object that handles a request for a specific page or action on a Web site.
Most people’s basic Web experience is with static HTML pages. When you request static HTML you pass to the Web server the name and path for a HTML document stored on it. The key notion is that each page on the Web site is a separate document on the server. With dynamic pages things can get much more interesting since there’s a much more complex relationship between path names and the file that responds. However, the approach of one path leading to one file that handles the request is a simple model to understand.
As a result, Page Controller has one input controller for each logical page of the Web site. That controller may be the page itself, as it often is in server page environments, or it may be a separate object that corresponds to that page.
How It Works
The basic idea behind a Page Controller is to have one module on the Web server act as the controller for each page on the Web site. In practice, it doesn’t work out to exactly one module per page, since you may hit a link sometimes and get a different page depending on dynamic information. More strictly, the controllers tie in to each action, which may be clicking a link or a button.
The Page Controller can be structured either as a script (CGI script, servlet, etc.) or as a server page (ASP, PHP, JSP, etc.). Using a server page usually combines the Page Controller and a Template View ( 350 ) in the same file. This works well for the Template View ( 350 ) but less well for the Page Controller because it’s more awkward to properly structure the module. If the page is a simple display, this isn’t a problem. However, if there’s logic involved in either pulling data out of the request or deciding which actual view to display, then you can end up with awkward scriptlet code in the server page.
One way of dealing with scriptlet code is to use a helper object. In this case the first thing the server page does is call the helper object to handle all the logic. The helper may return control to the original server page, or it may forward to a different server page to act as the view, in which case the server page is the request handler but most of the controller logic lies in the helper.
Another approach is to make a script the handler and controller. The Web server passes control to the script; the script carries out the controller’s responsibilities and finally forwards to an appropriate view to display any results.
The basic responsibilities of a Page Controller are:
• Decode the URL and extract any form data to figure out all the data for the action.
• Create and invoke any model objects to process the data. All relevant data from the HTML request should be passed to the model so that the model objects don’t need any connection to the HTML request.
• Determine which view should display the result page and forward the model information to it.
The Page Controller needn’t be a single class but can invoke helper objects. This is particularly useful if several handlers have to do similar tasks. A helper class can then be a good spot to put any code that would otherwise be duplicated.
There’s no reason that you can’t have some URLs handled by server pages and some by scripts. Any URLs that have little or no controller logic are best handled with a server page, since that provides a simple mechanism that’s easy to understand and modify. Any URLs with more complicated logic go to a script. I’ve come across teams who want to handle everything the same way: all server page or everything is a script. Any advantages of consistency in such an application are usually offset by the problems of either scriptlet-laden server pages or lots of simple pass-through scripts.
When to Use It
The main decision point is whether to use Page Controller or Front Controller ( 344 ). Of the two, Page Controller is the most familiar to work with and leads to a natural structuring mechanism where particular actions are handled by particular server pages or script classes. Your trade-off is thus the greater complexity of Front Controller ( 344 ) against the various advantages of Front Controller, most of which make a difference in Web sites that have more navigational complexity.
Page Controller works particularly well in a site where most of the controller logic is pretty simple. In this case most URLs can be handled with a server page and the more complicated cases with helpers. When your controller logic is simple, Front Controller ( 344 ) adds a lot of overhead.
It’s not uncommon to have a site where some requests are dealt with by Page Controllers and others are dealt with by Front Controllers ( 344 ), particularly when a team is refactoring from one to another. Actually, the two patterns mix without too much trouble.
Example: Simple Display with a Servlet Controller and a JSP View (Java)
A simple example of an Page Controller displays some information about something. Here we’ll show it displaying some information about a recording artist. The URL runs along the lines of http://www.thingy.com/recordingApp/artist?name=danielaMercury .
Figure 14.1. Classes involved in a simple display with a Page Controller servlet and a JSP view.
The Web server needs to be configured to recognize /artist as a call to ArtistController . In Tomcat you do this with the following code in the web.xml file:
Click here to view code image
The artist controller needs to implement a method to handle the request.
Click here to view code image
class ArtistController...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Artist artist = Artist.findNamed(request.getParameter("name"));
if (artist == null)
forward("/MissingArtistError.jsp", request, response);
else {
request.setAttribute("helper", new ArtistHelper(artist));
forward("/artist.jsp", request, response);
}
}
Although this is a very simple case, it covers the salient points. First the controller needs to create the necessary model objects to do their thing, here just finding the correct model object to display. Second it puts the right information in the HTTP request so that the JSP can display it properly. In this case it creates a helper and puts it into the request. Finally it forwards to the Template View ( 350 ) to handle the display. Forwarding is a common behavior, so it sits naturally on a superclass for all Page Controllers.
Click here to view code image
class ActionServlet...
protected void forward(String target,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
dispatcher.forward(request, response);
}
The main point of coupling between the Template View ( 350 ) and the Page Controller is the parameter names in the request to pass on any objects that the JSP needs.
The controller logic here is really very simple, but as it gets more complex we can continue to use the servlet as a controller. We can have a similar behavior for albums, with the twist that classical albums both have a different model object and are rendered with a different JSP. To do this behavior we can again use a controller class.
Click here to view code image
class AlbumController...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
Album album = Album.find(request.getParameter("id"));
if (album == null) {
forward("/missingAlbumError.jsp", request, response);
return;
}
request.setAttribute("helper", album);
if (album instanceof ClassicalAlbum)
forward("/classicalAlbum.jsp", request, response);
else
forward("/album.jsp", request, response);
}
Notice that in this case I’m using the model objects as helpers rather than creating a separate helper class. This is worth doing if a helper class is just a dumb forwarder to the model class. If you do it, though, make sure that the model class doesn’t contain any servlet-dependent code. Any servlet-dependent code should be in a separate helper class.
Example: Using a JSP as a Handler (Java)
Using a servlet as a controller is one route to take, but the most common route is to make the server page itself the controller. The problem with this approach is that it results in scriptlet code at the beginning of the server page and, as you may have gathered, I think that scriptlet code has the same relationship to well-designed software that professional wrestling has to sport.
Despite this you can make a server page as the request handler while delegating control to the helper to actually carry out the controller function. This preserves the simple property of having your URLs denoted by server pages. I’ll do this for the album display, using the URL of the form http://localhost:8080/isa/album.jsp?id=zero . Most albums are displayed directly with the album JSP, but classical recordings require a different display, a classical album JSP.
This controller behavior appears in a helper class to the JSP. The helper is set up in the album JSP itself.
Click here to view code image
album.jsp...
<jsp:useBean id="helper" class="actionController.AlbumConHelper"/>
<%helper.init(request, response);%>
The call to init sets the helper up to carry out the controller behavior.
Click here to view code image
class AlbumConHelper extends HelperController...
public void init(HttpServletRequest request, HttpServletResponse response) {
super.init(request, response);
if (getAlbum() == null) forward("missingAlbumError.jsp", request, response);
if (getAlbum() instanceof ClassicalAlbum) {
request.setAttribute("helper", getAlbum());
forward("/classicalAlbum.jsp", request, response);
}
}
Common helper behavior naturally sits on a helper superclass.
Click here to view code image
class HelperController...
public void init(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
protected void forward(String target,
HttpServletRequest request,
HttpServletResponse response)
{
try {
RequestDispatcher dispatcher = request.getRequestDispatcher(target);
if (dispatcher == null) response.sendError(response.SC_NO_CONTENT);
else dispatcher.forward(request, response);
} catch (IOException e) {
throw new ApplicationException(e);
} catch (ServletException e) {
throw new ApplicationException(e);
}
}
The key difference between the controller behavior here and that when using a servlet is that the handler JSP is also the default view and, unless the controller forwards to a different JSP, control reverts to the original handler. This is an advantage when you have pages where the JSP directly acts as the view most of the time and so there’s no forwarding to be done. The initialization of the helper acts to kick off any model behavior and set things up for the view later on. It’s a simple model to follow, since people generally associate a Web page with the server page that acts as its view. Often this also fits naturally with Web server configuration.
The call to initialize the handler is a little clumsy. In a JSP environment this awkwardness can be much better handled with a custom tag. Such a tag can automatically create an appropriate object, put it in the request, and initialize it. With that all you need is a simple tag in the JSP page.
<helper:init name = "actionController.AlbumConHelper"/>
The custom tag’s implementation then does the work.
Click here to view code image
class HelperInitTag extends HelperTag...
private String helperClassName;
public void setName(String helperClassName) {
this.helperClassName = helperClassName;
}
public int doStartTag() throws JspException {
HelperController helper = null;
try {
helper = (HelperController) Class.forName(helperClassName).newInstance();
} catch (Exception e) {
throw new ApplicationException("Unable to instantiate " + helperClassName, e);
}
initHelper(helper);
pageContext.setAttribute(HELPER, helper);
return SKIP_BODY;
}
private void initHelper(HelperController helper) {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
helper.init(request, response);
}
class HelperTag...
public static final String HELPER = "helper";
If I’m going to use custom tags like this, I might as well make them for property access too.
Click here to view code image
class HelperGetTag extends HelperTag...
private String propertyName;
public void setProperty(String propertyName) {
this.propertyName = propertyName;
}
public int doStartTag() throws JspException {
try {
pageContext.getOut().print(getProperty(propertyName));
} catch (IOException e) {
throw new JspException("unable to print to writer");
}
return SKIP_BODY;
}
class HelperTag...
protected Object getProperty(String property) throws JspException {
Object helper = getHelper();
try {
final Method getter = helper.getClass().getMethod(gettingMethod(property), null);
return getter.invoke(helper, null);
} catch (Exception e) {
throw new JspException
("Unable to invoke " + gettingMethod(property) + " - " + e.getMessage());
}
}
private Object getHelper() throws JspException {
Object helper = pageContext.getAttribute(HELPER);
if (helper == null) throw new JspException("Helper not found.");
return helper;
}
private String gettingMethod(String property) {
String methodName = "get" + property.substring(0, 1).toUpperCase() +
property.substring(1);
return methodName;
}
(You may think it’s better to use the Java Beans mechanism than to just invoke a getter using reflection. If so, you’re probably right ... and also probably intelligent enough to figure out how to change the method to do that.)
With the getting tag defined, I can use it to pull information out of the helper. The tag is shorter and eliminates any chance of my mizpelling “helper.”
Example: Page Handler with a Code Behind (C#)
The Web system in .NET is designed to work with the Page Controller and Template View ( 350 ) patterns, although you can certainly decide to handle Web events with a different approach. In this next example, I’ll use the preferred style of .NET, building the presentation layer on top of a domain using Table Module ( 125 ) and using data sets as the main carrier of information between layers.
This time we’ll have a page that displays runs scored and the run rate for one innings of a cricket match. As I know I’ll have many readers who are afflicted with no material experience of this art form, let me summarize by saying that the runs scored are the score of the batsman and the run rate is how many runs he scores divided by the number of balls he faces. The runs scored and balls faced are in the database; the run rate needs to be calculated by the application—a tiny but pedagogically useful piece of domain logic.
The handler in this design is an ASP.NET Web page, captured in a .aspx file. As with other server page constructs, this file allows you to embed programming logic directly into the page as scriptlets. Since you know I’d rather drink bad beer than write scriptlets, you know there’s little chance that I’d do that. My savior in this case is ASP.NET’s code behind mechanism that allows you to associate a regular file and class with the aspx page, signaled in the header of the aspx page.
Click here to view code image
<%@ Page language="c#" Codebehind="bat.aspx.cs" AutoEventWireup="false" trace="False"
Inherits="batsmen.BattingPage" %>
The page is set up as a subclass of the code behind class, and as such can use all its protected properties and methods. The page object is the handler of the request, and the code behind can define the handling by defining a Page_Load method. If most pages follow a common flow, I can define a Layer Supertype ( 475 ) that has a template method [ Gang of Four ] for this.
Click here to view code image
class CricketPage...
protected void Page_Load(object sender, System.EventArgs e) {
db = new OleDbConnection(DB.ConnectionString);
if (hasMissingParameters())
errorTransfer (missingParameterMessage);
DataSet ds = getData();
if (hasNoData (ds))
errorTransfer ("No data matches your request");
applyDomainLogic (ds);
DataBind();
prepareUI(ds);
}
The template method breaks down the request handling into a number of common steps. This way we can define a single common flow for handling Web requests, while allowing each Page Controller to supply implementations for the specific steps. If you do this, once you’ve written a few Page Controllers, you’ll know what common flow to use for the template method. If any page needs to do something completely different, it can always override the page load method.
The first task is to do validation on the parameters coming into the page. In a more realistic example this might entail initial sanity checking of various form values, but in this case we’re just decoding a URL of the form http://localhost/batsmen/bat.aspx?team=England&innings=2&match=905 . The only validation in this example is that the various parameters required for the database query are present. As usual I’ve been overly simplistic in the error handling until somebody writes a good set of patterns on validation—so here the particular page defines a set of mandatory parameters and the Layer Supertype ( 475 ) has the logic for checking them.
Click here to view code image
class CricketPage...
abstract protected String[] mandatoryParameters();
private Boolean hasMissingParameters() {
foreach (String param in mandatoryParameters())
if (Request.Params[param] == null) return true;
return false;
}
private String missingParameterMessage {
get {
String result = "<P>This page is missing mandatory parameters:</P>";
result += "<UL>";
foreach (String param in mandatoryParameters())
if (Request.Params[param] == null)
result += String.Format("<LI>{0}</LI>", param);
result += "</UL>";
return result;
}
}
protected void errorTransfer (String message) {
Context.Items.Add("errorMessage", message);
Context.Server.Transfer("Error.aspx");
}
class BattingPage...
override protected String[] mandatoryParameters() {
String[] result = {"team", "innings", "match"};
return result;
}
The next stage is to pull the data out of the database and put it in an ADO.NET disconnected data set object. Here this is a single query to the batting table.
Click here to view code image
class CricketPage...
abstract protected DataSet getData();
protected Boolean hasNoData(DataSet ds) {
foreach (DataTable table in ds.Tables)
if (table.Rows.Count != 0) return false;
return true;
}
class BattingPage...
override protected DataSet getData() {
OleDbCommand command = new OleDbCommand(SQL, db);
command.Parameters.Add(new OleDbParameter("team", team));
command.Parameters.Add(new OleDbParameter("innings", innings));
command.Parameters.Add(new OleDbParameter("match", match));
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataSet result = new DataSet();
da.Fill(result, Batting.TABLE_NAME);
return result;
}
private const String SQL =
@"SELECT * from batting
WHERE team = ? AND innings = ? AND matchID = ?
ORDER BY battingOrder";
Now the domain logic gets its turn to play, organized as a Table Module ( 125 ). The controller passes the retrieved data set to the Table Module ( 125 ) for processing.
Click here to view code image
class CricketPage...
protected virtual void applyDomainLogic (DataSet ds) {}
class BattingPage...
override protected void applyDomainLogic (DataSet dataSet) {
batting = new Batting(dataSet);
batting.CalculateRates();
}
At this point the controller part of the page handler is done. By this I mean, in classic Model View Controller ( 330 ) terms, that the controller should now hand over to the view to do display. In this design the BattingPage acts as both the controller and the view and the last call to prepareUI is part of the view behavior. I can now say farewell to this example in this pattern. However, I suspect you’ll find this to lack a certain dramatic closure, so you can find the example continued later (page 350 ).
Front Controller
A controller that handles all requests for a Web site.
In a complex Web site there are many similar things you need to do when handling a request. These things include security, internationalization, and providing particular views for certain users. If the input controller behavior is scattered across multiple objects, much of this behavior can end up duplicated. Also, it’s difficult to change behavior at runtime.
The Front Controller consolidates all request handling by channeling requests through a single handler object. This object can carry out common behavior, which can be modified at runtime with decorators. The handler then dispatches to command objects for behavior particular to a request.
How It Works
A Front Controller handles all calls for a Web site, and is usually structured in two parts: a Web handler and a command hierarchy. The Web handler is the object that actually receives post or get requests from the Web server. It pulls just enough information from the URL and the request to decide what kind of action to initiate and then delegates to a command to carry out the action (see Figure 14.2 ).
Figure 14.2. How the Front Controller works.
The Web handler is almost always implemented as a class rather than as a server page, as it doesn’t produce any response. The commands are also classes rather than server pages and in fact don’t need any knowledge of the Web environment, although they’re often passed the HTTP information. The Web handler itself is usually a fairly simple program that does nothing other than decide which command to run.
The Web handler can decide which command to run either statically or dynamically. The static version involves parsing the URL and using conditional logic; the dynamic version usually involves taking a standard piece of the URL and using dynamic instantiation to create a command class.
The static case has the advantage of explicit logic, compile time error checking on the dispatch, and lots of flexibility in the look of your URLs. The dynamic case allows you to add new commands without changing the Web handler.
With dynamic invocation you can put the name of the command class into the URL or you can use a properties file that binds URLs to command class names. The properties file is another file to edit, but it does make it easier to change your class names without a lot of searching through your Web pages.
A particularly useful pattern to use in conjunction with Front Controller is Intercepting Filter, described in [ Alur et al .]. This is essentially a decorator that wraps the handler of the front controller allowing you to build a filter chain (or pipeline of filters) to handle issues such as authentication, logging, and locale identification. Using filters allows you to dynamically set up the filters to use at configuration time.
Rob Mee showed me an interesting variation of Front Controller using a two stage Web handler separated into a degenerate Web handler and a dispatcher. The degenerate Web handler pulls the basic data out of the http parameters and hands it to the dispatcher in such a way that the dispatcher is completely independent of the Web server framework. This makes testing easier because test code can drive the dispatcher directly without having to run in a Web server.
Remember that both the handler and the commands are part of the controller. As a result the commands can (and should) choose which view to use for the response. The only responsibility of the handler is in choosing which command to execute. Once that’s done, it plays no further part in that request.
When to Use It
The Front Controller is a more complicated design than its obvious counterpart, Page Controller ( 333 ). It therefore needs a few advantages to be worth the effort.
Only one Front Controller has to be configured into the Web server; the Web handler does the rest of the dispatching. This simplifies the configuration of the Web server, which is an advantage if the Web server is awkward to configure. With dynamic commands you can add new commands without changing anything. They also ease porting since you only have to register the handler in a Web-server-specific way.
Because you create new command objects with each request, you don’t have to worry about making the command classes thread-safe. In this way you avoid the headaches of multi-threaded programming; however, you do have to make sure that you don’t share any other objects, such as the model objects.
A commonly stated advantage of a Front Controller is that it allows you to factor out code that’s otherwise duplicated in Page Controller ( 333 ). To be fair, however, you can also do much of this with a superclass Page Controller ( 333 ).
There’s just one controller, so you can easily enhance its behavior at runtime with decorators [ Gang of Four ]. You can have decorators for authentication, character encoding, internationalization, and so forth, and add them using a configuration file or even while the server is running. ([ Alur et al .] describe this approach in detail under the name Intercepting Filter. )
Further Reading
[ Alur et al .] give a detailed description of how to implement Front Controller in Java. They also describe Intercepting Filter, which goes very well with Front Controller.
A number of Java Web frameworks use this pattern. An excellent example appears in [ Struts ].
Example: Simple Display (Java)
Here’s a simple case of using Front Controller for the original and innovative task of displaying information about a recording artist. We’ll use dynamic commands with a URL of the form http://localhost:8080/isa/music?name=barelyWorks&command=Artist . The command parameter tells the Web handler which command to use.
Figure 14.3. The classes that implement Front Controller .
We’ll begin with the handler, which I’ve implemented as a servlet.
Click here to view code image
class FrontServlet...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
FrontCommand command = getCommand(request);
command.init(getServletContext(), request, response);
command.process();
}
private FrontCommand getCommand(HttpServletRequest request) {
try {
return (FrontCommand) getCommandClass(request).newInstance();
} catch (Exception e) {
throw new ApplicationException(e);
}
}
private Class getCommandClass(HttpServletRequest request) {
Class result;
final String commandClassName =
"frontController." + (String) request.getParameter("command") + "Command";
try {
result = Class.forName(commandClassName);
} catch (ClassNotFoundException e) {
result = UnknownCommand.class;
}
return result;
}
The logic is straightforward. The handler tries to instantiate a class named by concatenating the command name and “Command.” Once it has the new command it initializes it with the necessary information from the HTTP server. I’ve passed in what I need for this simple example. You may well need more, such as the HTTP session. If you can’t find a command, I’ve used the Special Case ( 496 ) pattern and returned an unknown command. As is often the case, Special Case ( 496 ) allows you to avoid a lot of extra error checking.
Commands share a fair bit of data and behavior. They all need to be initialized with information from the Web server.
Click here to view code image
class FrontCommand...
protected ServletContext context;
protected HttpServletRequest request;
protected HttpServletResponse response;
public void init(ServletContext context,
HttpServletRequest request,
HttpServletResponse response)
{
this.context = context;
this.request = request;
this.response = response;
}
They can also provide common behavior, such as a forward method, and define an abstract process command for the actual commands to override.
Click here to view code image
class FrontCommand...
abstract public void process()throws ServletException, IOException ;
protected void forward(String target) throws ServletException, IOException
{
RequestDispatcher dispatcher = context.getRequestDispatcher(target);
dispatcher.forward(request, response);
}
The command object is very simple, at least in this case. It just implements the process method, which involves invoking the appropriate behavior on the model objects, putting the information needed for the view into the request, and forwarding to a Template View ( 350 ).
Click here to view code image
class ArtistCommand...
public void process() throws ServletException, IOException {
Artist artist = Artist.findNamed(request.getParameter("name"));
request.setAttribute("helper", new ArtistHelper(artist));
forward("/artist.jsp");
}
The unknown command just brings up a boring error page.
Click here to view code image
class UnknownCommand...
public void process() throws ServletException, IOException {
forward("/unknown.jsp");
}
Template View
Renders information into HTML by embedding markers in an HTML page.
Writing a program that spits out HTML is often more difficult than you might imagine. Although programming languages are better at creating text than they used to be (some of us remember character handling in Fortran and standard Pascal), creating and concatenating string constructs is still painful. If there isn’t much to do, it isn’t too bad, but a whole HTML page is a lot of text manipulation.
With static HTML pages—those that don’t change from request to request—you can use nice WYSIWG editors. Even those of us who like raw text editors find it easier to just type in the text and tags rather than fiddle with string concatenation in a programming language.
Of course the issue is with dynamic Web pages—those that take the results of something like database queries and embed them into the HTML. The page looks different with each result, and as a result regular HTML editors aren’t up to the job.
The best way to work is to compose the dynamic Web page as you do a static page but put in markers that can be resolved into calls to gather dynamic information. Since the static part of the page acts as a template for the particular response, I call this a Template View.
How It Works
The basic idea of Template View is to embed markers into a static HTML page when it’s written. When the page is used to service a request, the markers are replaced by the results of some computation, such as a database query. This way the page can be laid out in the usual manner, often with WYSIWYG editors, often by people who aren’t programmers. The markers then communicate with real programs to put in the results.
A lot of tools use Template View. As a result this pattern isn’t about how to build one yourself, but about how to use one effectively and what the alternative is.
Embedding the Markers
There are a number of ways markers can be placed in the HTML. One is to use HTML-like tags. This works well with WYSIWYG editors because they realize that anything between the angled brackets (<>) is special and so either ignore it or treat it differently. If the tags follow the rules for well-formed XML you can also use XML tools on the resulting document (providing your HTML is XHMTL, of course).
Another way to do this is to use special text markers in the body text. WYSIWYG editors treat that as regular text, still ignoring it but probably doing annoying things to it like spell checking. The advantage is that the syntax can be easier than the clunky syntax of HTML/XML.
Many environments provide the set of tags you use but more and more platforms now give you the ability to define your own tags and markers so you can design them to fit in with your particular needs.
One of the most popular forms of Template View is a server page such as ASP, JSP, or PHP. These actually go a step further than the basic form of a Template View in that they allow you to embed arbitrary programming logic, referred to as scriptlets, into the page. In my view, however, this feature is actually a big problem and you’re better off limiting yourself to basic Template View behavior when you use server page technology.
The most obvious disadvantage of putting a lot of scriptlets into a page is that it eliminates the possibility of nonprogrammers editing the page. This is particularly important when you’re using graphic designers for the page design. However, the biggest problems of embedding scriptlets into the page come from the fact that a page is poor module for a program. Even with an object-oriented language the page construct loses you most of the structural features that make it possible to do a modular design either in OO or in procedural style.
Even worse, putting a lot of scriptlets into the page makes it too easy to mingle the different layers of an enterprise application. When domain logic starts turning up on server pages it becomes far too difficult to structure it well and far too easy to duplicate it across different server pages. All in all, the worst code I’ve seen in the last few years has been server page code.
Helper Object
The key to avoiding scriptlets is to provide a regular object as a helper to each page. This helper has all the real programming logic. The page only has calls into it, which simplifies the page and makes it a more pure Template View. The resulting simplicity allows nonprogrammers to edit the page and programmers to concentrate on the helper. Depending on the actual tool you’re using, you can often reduce all the templates in a page to HTML/XML tags, which keeps the page more consistent and more amenable to tool support.
This sounds like a simple and commendable principle, but as ever quite a few dirty issues make things more complicated. The simplest markers are those that get some information from the rest of the system and put in the correct place on the page. They are easily translated into calls to the helper that result in text, (or something that’s trivially turned into text), and the engine places the text on the page.
Conditional Display
A more knotty issue is conditional page behavior. The simplest case is the situation where something is displayed only if a condition is true. That might be some kind of conditional tag along the lines of <IF condition = "$pricedrop > 0.1"> ...show some stuff </IF> . The trouble with this is that when you start having conditional tags like this, you start going down the path of turning the templates into a programming language in and of themselves. This leads you into all the same problems you face when you embed scriptlets in the page. If you need a full programming language, you might as well use scriptlets, but you know what I think of that idea!
As a result, I see purely conditional tags as a bad smell, something you should try to avoid. You can’t always avoid them, but you should try to come up with something more focused than a general purpose <IF> tag.
If you’re displaying some text conditionally, one option is to move the condition into the helper. The page will then always insert the result of the call into helper. It’s just that if the condition isn’t true the helper will send back an empty string, but this way the helper holds all the logic. This approach works best if there’s no markup for the returned text or it’s enough to return empty markup that gets ignored by the browser.
This doesn’t work if, say, you want to highlight good-selling items in a list by putting their names in bold. In such a situation you always need the names displayed but sometimes you want the special markup. One way to get it is to have the helper generate the markup. This keeps all the logic out of the page, at the cost of moving the choice of highlighting mechanism away from the page designer and giving it to the programming code.
In order to keep the choice of HTML in the hands of the page design, you need some form of conditional tag. However it’s important to look beyond a simple <IF> . A good route to go is a focused tag, so rather than a tag that looks like this:
Click here to view code image
you have one like
Click here to view code image
In either case it’s important that the condition be done based on a single Boolean property of the helper. Putting any more complex expression into the page is actually putting the logic into the page itself.
Another example would be putting information on a page that depends on the locale on which the system is running. Consider some text that should only be shown in the United States or Canada, which, rather than
Would be something like
Iteration
Iterating over a collection presents similar issues. If you want a table where each line corresponds to a line item on an order, you need a construct that allows easy display of information for each line. Here it’s hard to avoid a general iteration over a collection tag, but it usually works simply enough to fit in quite well.
Of course the kinds of tag you have to work with are often limited by the environment you’re in. Some environments give you a fixed set of templates, in which case you may be more limited than you would like in following these kinds of guidelines. In other environments, however, you may have more choice in the tags to use; many of them even allow you to define your own tag libraries.
When to Process
The name Template View brings out the fact that the primary function of this pattern is to play the view in Model View Controller ( 330 ). For many systems the Template View should only play the view. In simpler systems it may be reasonable for it to play the controller, and possibly even the model, although I would strive to separate model processing as much as possible. Where Template View is taking on responsibilities beyond the view, it’s important to ensure that these responsibilities are handled by the helper, not by the page. Controller and model responsibilities involve program logic, which program logic everywhere, should sit in the helper.
Any template system needs extra processing by the Web server. This can either be done by compiling the page after it’s created, compiling the page or on its first request, or by interpreting the page on each request. Obviously the latter isn’t a good idea if the interpretation takes a while to do.
One thing to watch with Template View is exceptions. If an exception works its way up to the Web container, you may find yourself with a half-handled page that provides some decidedly odd output to the calling browser instead of a redirect. You need to look into how your Web server handles exceptions; if it does something strange, catch all exceptions yourself in the helper class (yet another reason to disdain scriptlets.)
Using Scripts
Although server pages are one of the most common forms of Template View these days, you can write scripts in a Template View style. I’ve seen a fair bit of Perl done this way. Most noticeably demonstrated by perl’s CGI.pm, the trick is to avoid concatenating strings by having function calls that output the appropriate tags to the response. This way you can write the script in your programming language and avoid the mess of interspersing print strings with programming logic.
When to Use It
For implementing the view in Model View Controller ( 330 ) the main choice is between Template View and Transform View ( 361 ). The strength of Template View is that it allows you to compose the content of the page by looking at the page structure. This seems to be easier for most people to do and to learn. In particular it nicely supports the idea of a graphic designer laying out a page with a programmer working on the helper.
Template View has two significant weaknesses. First, the common implementations make it too easy to put complicated logic in the page, thus making it hard to maintain, particularly by nonprogrammers. You need good discipline to keep the page simple and display oriented, putting logic in the helper. The second weakness is that Template View is harder to test than Transform View ( 361 ). Most implementations of Template View are designed to work within a Web server and are very difficult or impossible to test otherwise. Transform View ( 361 ) implementations are much easier to hook into a testing harness and test without a running Web server.
In thinking about a view you also need to consider Two Step View ( 365 ). Depending on your template scheme you may be able to implement this pattern using specialized tags. However, you may find it easier to implement it based on a Transform View ( 361 ). If you’re going to need Two Step View ( 365 ) you need to take that into account in your choice.
Example: Using a JSP as a View with a Separate Controller (Java)
When using a JSP as a view only, it’s always be invoked from a controller rather than directly from the servlet container. Thus, it’s important to pass to the JSP any information it will need to figure out what to display. A good way to do this is to have the controller create a helper object and pass it to the JSP using the HTTP request. We’ll show this with the simple display example from Page Controller ( 333 ). The Web-handling method for the servlet looks like this:
Click here to view code image
class ArtistController...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
Artist artist = Artist.findNamed(request.getParameter("name"));
if (artist == null)
forward("/MissingArtistError.jsp", request, response);
else {
request.setAttribute("helper", new ArtistHelper(artist));
forward("/artist.jsp", request, response);
}
}
As far as the Template View is concerned the important behavior is creating the helper and placing it in the request. The server page can now reach the helper with the useBean tag.
<jsp:useBean id="helper" type="actionController.ArtistHelper" scope="request"/>
With the helper in place we can use it to access the information we need to display. The model information the helper needs was passed to it when it was created.
Click here to view code image
class ArtistHelper...
private Artist artist;
public ArtistHelper(Artist artist) {
this.artist = artist;
}
We can use the helper to get appropriate information from the model. In the simplest case we provide a method to get some simple data, such as the artist’s name.
Click here to view code image
class ArtistHelper...
public String getName() {
return artist.getName();
}
Then we access this information by a Java expression.
<%=helper.getName()%>or a property
The choice between properties or expressions depends on who is editing the JSP. Programmers find expressions easy to read and more compact, but HTML editors may not be able to handle them. Nonprogrammers will probably prefer tags, since they fits in the general form of HTML and leave less room for confusing errors.
Using a helper is one way to remove awkward scriptlet code. If you want to show a list of albums for an artist, you need to run a loop, which you can do with a scriptlet in the server page.
Click here to view code image
-
<%
for (Iterator it = helper.getAlbums().iterator(); it.hasNext();) {
Album album = (Album) it.next();%>
- <%=album.getTitle()%> <% } %>
Frankly, this mix of Java and HTML is really horrible to read. An alternative is to move the for loop to the helper.
Click here to view code image
class ArtistHelper...
public String getAlbumList() {
StringBuffer result = new StringBuffer();
result.append("<UL>");
for (Iterator it = getAlbums().iterator(); it.hasNext();) {
Album album = (Album) it.next();
result.append("<LI>");
result.append(album.getTitle());
result.append("</LI>");
}
result.append("</UL>");
return result.toString();
}
public List getAlbums() {
return artist.getAlbums();
}
I find this easier to follow because the amount of HTML is quite small. It also allows you to use a property to get the list. Many people don’t like putting HTML code in helpers. While I prefer not to, given the choice between this and scriptlets I’d choose HTML in helpers any day or night.
The best route to go is a specialized tag for iteration.
Click here to view code image
Match id:
The table is a little more complicated, but actually works easily in practice because of the graphical design facilities in Visual Studio. Visual Studio provides a data grid control that can be bound to a single table from a data set. I can do this binding in the `prepareUI` method that’s called by the `Page_Load` method.
Click here to view code image
class BattingPage...
override protected void prepareUI(DataSet ds) {
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
The batting class is a _Table Module ( 125 )_ that provides domain logic for the batting table in the database. Its data property is the data from that table enriched by domain logic from _Table Module ( 125 )._ Here the enrichment is the run rate, which is calculated rather than stored in the database.
With the ASP.NET data grid you can select which table columns you wish to display in the Web page, together with information about the table’s appearance. In this case we can select name, runs, and rate columns.
Click here to view code image
Artist:
"); } catch (IOException e) { throw new JspException("unable to print start"); } return EVAL\_BODY\_INCLUDE; } public int doEndTag() throws JspException { try { pageContext.getOut().print("
"); } catch (IOException e) { throw new JspException("unable to print end"); } return EVAL\_PAGE; } For those that haven’t indulged, a custom tag works by implementing hook methods called at the beginning and the end of the tagged text. This tag simply wraps its body content with an `` tag. A more complex tag, such as the field, can take an attribute. The attribute is tied into the tag class using a setting method. Click here to view code image class FieldTag... private String label; public void setLabel(String label) { this.label = label; } Once the value is set, you can use it in the output. Click here to view code image class FieldTag... public int doStartTag() throws JspException { try { pageContext.getOut().print("
" + label + ": "); } catch (IOException e) { throw new JspException("unable to print start"); } return EVAL\_BODY\_INCLUDE; } public int doEndTag() throws JspException { try { pageContext.getOut().print("
"); } catch (IOException e) { throw new JspException("how are checked exceptions helping me here?"); } return EVAL\_PAGE; } The `Table` is the most sophisticated of the tags. As well as allowing the JSP writer to choose which columns to put in the table, it highlights alternate rows. The tag implementation acts as the second stage, so the highlighting is done there so that a system-wide change can be made globally. The `Table` tag takes attributes for the name of the collection property, the object on which the collection property sits, and a comma-separated list of column names. Click here to view code image class TableTag... private String collectionName; private String hostName; private String columns; public void setCollection(String collectionName) { this.collectionName = collectionName; } public void setHost(String hostName) { this.hostName = hostName; } public void setColumns(String columns) { this.columns = columns; } I made a helper method to get a property out of an object. There’s a good argument for using the various classes that support Java beans, rather than just invoking a “getsomething” method, but this will do for the example. Click here to view code image class TableTag... private Object getProperty(Object obj, String property) throws JspException { try { String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1); Object result = obj.getClass().getMethod(methodName, null).invoke(obj, null); return result; } catch (Exception e) { throw new JspException("Unable to get property " + property + " from " + obj); } } This tag doesn’t have a body. When it’s called it pulls the named collection out of the request property and iterates through the collection to generate the rows of the table. Click here to view code image class TableTag... public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.print("