JSP Tag Libraries

Скачать в pdf «JSP Tag Libraries»
15.4.2 Generalizing your tags


There is good reason to assume that if you need a specific action, then, most likely, that action is a specific case of a more generalized need. In chapter 6 we developed a tag whose role is to flush the output stream that is connected to the user; but we can generalize that. Flushing the output stream was a method call, but it was also a command that we gave to the JspWriter object. Command objects are a known design pattern2 that can be useful within the JSP programming environment.


Command is a behavioral design pattern whose intent is to encapsulate a request as an object—in everyday cases, this means a method call on an object. By encapsulating a request as an object, you can bridge the differences between systems and hide complex operations within an easy-to-use interface. (Additional uses for the Command pattern exist, but we will not go into them here.)

A simple command pattern example


To make the Command pattern concrete, let’s take a look at a basic example. We have a command class named sendMaii whose job is to send email. sendMaii has three command parameters:


■    to—the email’s receiving end


■    subject—the email’s subject


■    body—the email’s body


and has an execute method to send the email.


Using the SendMaii command from within a Java program looks like:


SendMaii cmd = new SendMaii(); cmd.setTo(«some@address»); cmd.setSubject(«some subj ect»); cmd.setBody( «Some body …»); cmd.execute();


It is possible to implement the first four lines using the standard JSP <jsp:use-Bean> and <jsp:setProperty/> tags presented in chapter
2. We can also instantiate the command and set its parameters within a servlet and send the command to

Скачать в pdf «JSP Tag Libraries»