JSP Tag Libraries

Скачать в pdf «JSP Tag Libraries»
BodyTags and the JSP runtime engine (behind the scenes)

Having gone through an in-depth discussion of the life cycle of BodyTags in chapter
4, you might think we know everything possible about JSP engines handling BodyTags, right? Although we learned when and why the runtime engine calls the methods of a BodyTag, what we didn’t cover was how the engine manages the output of BodyTags. Since BodyTags can modify the contents of their body (which can contain other tags or scriptlets) these modifications must be managed by the engine until the tags are finished changing it. At that point they can be aggregated and sent to the user. This process requires a little juggling by the runtime engine in order to produce the predicted results for pages containing BodyTags. Let’s take a look at that juggling act.

No matter what the content of a tag’s body, whether it be scriptlets, static HTML, or other custom tags, the JSP engine will first process this content (as if it were anywhere else in the JSP) and then pass the results of that processing to the tag as its BodyContent. This is not such a simple task. How can all the scriptlets and tags suddenly hand over their results to the BodyTag? Redirecting all this output to a new location seems to be a daunting task, but the solution chosen by the JSP specification made it all much simpler than might be imagined.

The JSP specification’s solution works on the premise that all output flowing to the user must be written to the implicit out object. When the JSP engine begins processing the body of a BodyTag, it swaps the implicit out with a new JspWriter that writes to a temporary holding tank. All the code and/or tags within a BodyTag’s body that “think” they are writing to the user, are really writing to some storage managed by the JSP engine. Later, when the body processing is completed, the engine gives the enclosing BodyTag access to this storage which now contains all the processed output of the tag’s body. Indeed, the JSP specification defines a special JspWriter derivative called BodyContent, whose role is to serve as this holding tank and to be the implicit out variable during the processing of a BodyTag’s body. The BodyContent provides methods that let its developer access the content written into the BodyContent, as well as erase this content when needed. The problem becomes more complex in the face of BodyTag recursion—meaning BodyTag whose body encloses yet another BodyTag, and whose body encloses yet another BodyTag, and so forth. All these tags together force the JSP runtime to remember each tag’s BodyContent and return to it when the enclosed tag is finished. To solve that, the JSP runtime is managing a stack of all the active JspWriter instances in the current page. In this way it can always pop the enclosed BodyContent out of the stack and return to the previous JspWriter.

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