Java Reference
In-Depth Information
pattern allows the other elements of the architecture to handle commands
generically. In short, we let the computer do the work.
The interface for a command does conform to a well-known design pat-
tern. There are getters for output parameters, setters for input parameters, an
initialize
method, and an
execute
method. Some architectures choose not
to implement an
initialize
method, and some use a method called
prepare-
ToCommit
. Given a list of parameters, it is easy to create a wizard or super class
to build the base commands. The commands can then be invoked and
accessed by other servlets.
In this example, I have left the Structured Query Language (
SQL
) in the
commands, but it would be just as easy to express this architecture with state-
less session beans wrapping an
EJB
. The difference between the business
model in this example and the one in the previous servlet is tremendous. In
our case, the wizard will probably maintain the command beans. Changes in
the user interface will no longer affect the model.
Our servlet is getting much simpler, too. Here is the
performTask
method
for the servlet that calls our command:
public void performTask(
HttpServletRequest request,
HttpServletResponse response) {
try {
PostListCommand postList = new PostListCommand();
postList.initialize();
postList.execute();
performTask
is getting smaller. First, we need to allocate our
PostListCommand
object, which is performing our database access. Then, we initialize and load it:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD "
+ "HTML 4.0 Transitional//EN\">\n"
+ "<HTML>\n"
+ "<HEAD><TITLE>Message Board</TITLE></HEAD>\n"
+ "<BODY>\n");
// display the commands results
out.println("<h1>Message board posts</h1>");
out.println("<TABLE border=\"1\">");
out.println("<TD><b>subject</b></TD>\n");
out.println("<TD><b>author</b></TD>\n");
out.println("<TD><b>board</b></TD>\n");
for (int i=0; i<postList.getSize(); i++) {