«    »

Creating Custom Tags Using JSP

Java Server Pages (JSP) is a Java technology for rendering dynamic web pages. Unlike servlets written directly in Java, JSP files contain special markup to identify java or JSP code. The normal (non-markup) text is interpreted as HTML. Early in JSP's evolution, custom tags were introduced as a way of providing reusable functionality, particularly reusable UI widgets, across JSP files. The original mechanism for creating these custom tags was very clunky: each tag had to be written in Java code (similar to servlets) and required extra configuration in XML to package into a tag library.

As of JSP version 2.0, available since Java EE 1.4, there is now support for creating custom tags using only the JSP syntax. No Java or XML is required. Each individual custom tag corresponds to a tag file, which is nothing more than a JSP file with a .tag extension located in a special directory within the WAR file: /WEB-INF/tags.

Attributes can be supplied to the tag file using a JSP directive <%@attribute name="<some-name>" required="{true|false}"%>. Attributes are referenced within the tag file like any other JSP variable using EL (the expression language).

This JSP tag library within your WAR can be referenced by other JSPs using the taglib directive: <%@taglib tagdir="/WEB-INF/tags" prefix="tags"%>.

The following example shows this in action. First the custom tag file WEB-INF/tags/title.tag:

<%@attribute name="title" required="true"%>
<%@tag description="Standard Title" pageEncoding="UTF-8"%>

<h1>${title}</h1>

Now a normal JSP file that uses this custom tag:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags"%>
<html>
<body>
<tags:title title="Hello World"/>
</body>
</html>

Prior to JSP 2.0 I have made reusable JSP fragments using the import directive, but this new mechanism is just as simple and much more convenient. Smart JSP editors can in fact provide lookup/completion functionality when you are invoking your custom tags.

The capabilities of these custom tags go far beyond what I have shown here. For more information see Sun's Custom Tags Tutorial.

If you find this article helpful, please make a donation.

One Comment on “Creating Custom Tags Using JSP”

  1. Sachin says:

    Thanks man!! Have been looking for this from long time… TX

«    »