Iterative Tags

A common requirement for Web pages is to provide a variable number of items in a common format. Although the JSTL core and XML <forEach> tags can now be used for iterations, there are occasions when you will need to write your own custom tags to perform iteration.

Iterative custom tags interact with the processing of the start and end tags to ask for the tag body to be processed again, and again, and again….

An iterative tag must implement the IterationTag interface. This is most commonly achieved by sub-classing the BodyTagSupport class. The doAfterBody(), method must return IterationTag.EVAL_BODY_AGAIN to process the body again or Tag.SKIP_BODY to stop the iteration. Typically, the doAfterBody() method will change the data for each iteration loop.

The iteration tag has complete control over the body content of the page because it can return values from the page interaction methods, such as doAfterBody() and then tell the JSP processor how to continue processing the page.

The default behavior for the BodyTagSupport class is to buffer the body text of the custom tag and discard it when the end tag is processed. You will have to override this behavior in your custom tag so that it outputs the body text either every time around the iteration loop or once at the end of the tag.

The BodyTagSupport class stores the body content in a BodyTagSupport class instance variable called bodyContent (class javax.servlet.jsp.tagext.BodyContent). The BodyContent class extends the JSPWriter class.

The following code illustrates the normal approach to writing the buffered body content to the Web page:

JspWriter out = getPreviousOut();
out.print(bodyContent.getString());
bodyContent.clearBody();

The steps required are as follows:

1.
Obtain the JSPWriter object that can be used to output the body content text (the getPreviousOut() method).

2.
Print the string data buffered in the body content.

3.
Clear the body content text after it has been written to the page; otherwise, it will be written more than once.

Typically, the body content is added to the page from within the doAfterBody() method. This keeps the size of the body content down because it is flushed to the page with each iteration and saves on memory usage. If the body content cannot be determined until all of the iterations have completed (or the tag is not an iterative one), you will have to write it to the page in the doEndTag() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.67.5