Tag Files

Including file in a JSP page is such a common task that Tag Files have been created to perform this operation in a more friendly way than using <jsp:include> or even <c:import>.

There are a few ways to create and use Tag Files, this is probably the easiest one:
  1. A Tag File should be created in the WEB-INF/tags directory
  2. Its name should be in the form filename.tag, the content is the same as an already seen included file (no html and body tags)
  3. The including JSP page should declare that it is about to use Tag Files through the taglib directive with a tagdir attribute; then it could use a tag for the required file inclusion
For instance, let's create a one liner header.tag file in WEB-INF/tags:
<h3>My fancy header</h3>
In another JSP page we can include it:
<!-- ... -->
<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>
<!-- ... -->
<myTags:header/>
But the real cool thing about Tag Files is how we pass parameters from the including file to the included one: we use tag attributes.

In the caller we add an attribute named as the parameter to the tag:
<myTags:Header subTitle="We take the String out of SOAP" />
In the Tag File we declare the attribute using the specific directive, and then we use it in the tag body, like this:
<%@ attribute name="subTitle" required="true" rtexprvalue="true" %>
<h3>My fancy and cool header</h3>
<p><b><i>${subTitle}</i></b></p>
The attribute directive specify the name of the attribute, if it is mandatory or optional, and if it must be a String literal or could be an expression.

If we expect a huge attribute value, such as it would be messy to put it as an attribute value in the tag, we could rely on the jsp:doBody tag and pass it as body associated to the Tag File.
We change our tag definition in this way:
<%@ attribute name="subTitle" required="true" rtexprvalue="true" %>
<h3>My fancy and cool header</h3>
<p><b><i>${subTitle}</i></b></p>
<p><i><jsp:doBody/></i></p>
And we use it with a body:
<myTags:header subTitle="We take the String out of SOAP">
<p>This is what you see when you get the header.</p>
<p>You can put so many lines of text as required</p>
keeping the code readable. 
</myTags:header>
We can state that we don't want our Tag File accepting a body, using the tag directive in its definition:
<%@ tag body-content="empty" %>
Chapter ten of Head First Servlet and JSP is a good place where to look for more information on Tag Files.

No comments:

Post a Comment