Java Reference
In-Depth Information
3.1
Introducing the controller component
Core
Java
EE
Patterns
describes a
controller
as a component that “interacts with a client,
controlling and managing the handling of each request,” and tells us that it's used in
both presentation-tier and business-tier patterns.
1
In general, a controller does the following:
Accepts requests
■
Performs any common computations on the request
■
Selects an appropriate request handler
■
Routes the request so that the handler can execute the relevant business logic
■
May provide a top-level handler for errors and exceptions
■
You'll find controllers to be handy in a variety of applications. For example, in a
presentation-tier pattern, a web controller accepts
HTTP
requests and extracts
HTTP
parameters, cookies, and
HTTP
headers, perhaps making the
HTTP
elements easily
accessible to the rest of the application. A web controller determines the appropri-
ate business logic component to call based on elements in the request, perhaps
with the help of persistent data in the
HTTP
session, a database, or some other
resource. The Apache Struts framework is an example of a web controller.
Another common use for a controller is to handle applications in a business-tier
pattern. Many business applications support several presentation layers.
HTTP
clients
may handle web applications. Swing clients may handle desktop applications. Behind
these presentation tiers, there's often an application controller, or state machine. Pro-
grammers implement many Enterprise JavaBean (
EJB
) applications this way. The
EJB
tier has its own controller, which connects to different presentation tiers through a
business façade or delegate.
Given the many uses for a controller, it's no surprise that controllers crop up in a
number of enterprise architecture patterns, including Page Controller, Front Control-
ler, and Application Controller.
2
The controller you'll design here could be the first
step in implementing any of these classic patterns. Let's work through the code for
the simple controller, to see how it works, and then try a few tests. If you'd like to fol-
low along and run the tests as you go, all the source code for this chapter is available at
SourceForge (
http://junitbook.sf.net)
. See appendix A for more about setting up the
source code.
3.1.1
Designing the interfaces
Looking over the description of a controller, four objects pop out: the
Request
,
the
Response
, the
RequestHandler
, and the
Controller
. The
Controller
accepts
1
Deepak Alur, John Crupi, and Dan Malks,
Core Java EE Patterns: Best Practices and Design Strategies
(Upper
Saddle River, NJ: Prentice Hall, 2001).
2
Martin Fowler,
Patterns of Enterprise Application Architecture
(Boston: Addison-Wesley, 2003).