Professional Java Server Programming J2EE Edition Chapter 12
Although we developed it from our previous examples, this is close to a generic solution for list iteration, isn't
it? It conceals the looping from the JSP and makes the successive list values and indices available. With minor
changes, this class could take a Collection, or a Swing ListModel, and make it available to any JSP.
The main reason that this tag is so generic is that it doesn't generate markup. The more the JSP can control its
output, the more useful a tag extension is.
Body Tags That Filter Their Content
Another idiomatic use of body tags is to perform filtering or other processing on their body content. This
could be a simple text transformation, or could even interpret the tag's content as a custom language. The
following simple example takes the tag's body content and writes it, reversed, into the calling JSP page.
Implementing the reversal is trivial; all we need to do is obtain the body content as a String, use it to
initialize a StringBuffer, and call the StringBuffer's reverse() method before writing out the
resulting String:
package tagext;
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
// Simple body tag to reverse its content
public class ReverseTag extends BodyTagSupport {
/*
* Called after processing of body content is complete.
* We use it to obtain the tag's body content and write
* it out reversed.
*/
public int doEndTag() throws JspTagException {
BodyContent bodyContent = getBodyContent();
// Do nothing if there was no body content
if (bodyContent != null) {
StringBuffer output = new StringBuffer(bodyContent.getString());
output.reverse();
try {
bodyContent.getEnclosingWriter().write(output.toString());
}
catch (IOException ex) {
throw new JspTagException("Fatal IO error");
}
}
// Process the rest of the page
return EVAL_PAGE;
}
}
The tag library entry is also very simple. There are no variables requiring a TagExtraInfo class, and
no attributes:
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|