Custom Tags 1 – Skills for Tag Files


This post presents the basic skills of JSP Tag Files.

Create a Tag File

Step 1. Write a file simple.tag inside the WEB-INF/tags directory.

<%-- simple.tag --%>
<p>Greetings from a JSP Tag File!!</p>

Step 2. Call it!

<%-- output.jsp --%>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<html>
  <body>
    <my:simple />
  </body>
</html>
Invoking a tag file

Invoking a tag file

Passing attributes

Attributes are declared as directives.

<%-- simple.tag --%>
<%@ attribute name="friend" %>
<p>Hello ${friend}, greetings from a JSP Tag File!!</p>
<%-- output.jsp --%>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<html>
  <body>
    <my:simple friend="Niko" />
  </body>
</html>
Passing an attribute to a tag file

Passing an attribute to a tag file

You may also mark the attribute as required,

<%@ attribute name="friend" required="true" %>

and specify that its value should be evaluated at runtime.

<%@ attribute name="friend" rtexprvalue="true" %>

Processing its body

The body-content may be defined as empty, scriptless or tagdependent (plain text).

<%-- simple.tag --%>
<%@ tag body-content="scriptless" %>
<p>This is my body: <jsp:doBody /></p>
<%-- output.jsp --%>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<html>
  <body>
    <my:simple>Some useful content</my:simple>
  </body>
</html>
Accessing the body of a tag file

Accessing the body of a tag file

Passing dynamic attributes

The user of the tag may send extra attributes that are not explicitly defined with a directive. These attributes are called dynamic ones. A simple application would be to list them.

<%-- simple.tag --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ tag dynamic-attributes="map" %>
<p>These are the dynamic attributes:</p>
<ol>
  <c:forEach var="item" items="${map}">
    <li>${item.key}</li>
  </c:forEach>
</ol>
<%-- output.jsp --%>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<html>
  <body>
    <my:simple name="Niko" java="100%" />
  </body>
</html>
Dynamic attributes in a tag file

Dynamic attributes in a tag file

One Response to Custom Tags 1 – Skills for Tag Files

  1. […] Custom Tags 1 – Create a Tag File […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: