The Java EE 5 Tutorial

Declaring Tag Libraries

This section explains how to use XML namespaces to declare tag libraries.

In standard syntax, the taglib directive declares tag libraries used in a JSP page. Here is an example of a taglib directive:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

This syntax is not allowed in JSP documents. To declare a tag library in a JSP document, you use the xmlns attribute, which is used to declare namespaces according to the XML standard:

...
xmlns:c="http://java.sun.com/jsp/jstl/core"
...

The value that identifies the location of the tag library can take three forms:

The URN of the form urn:jsptld:path points to one tag library packaged with the application:

xmlns:u="urn:jsptld:/WEB-INF/tlds/my.tld"

The URN of the form urn:jsptagdir:path must start with /WEB-INF/tags/ and identifies tag extensions (implemented as tag files) installed in the /WEB-INF/tags/ directory or a subdirectory of it:

xmlns:u="urn:jsptagdir:/WEB-INF/tags/mytaglibs/"

You can include the xmlns attribute in any element in your JSP document, just as you can in an XML document. This capability has many advantages:

The books.jspx page declares the tag libraries it uses with the xmlns attributes in the root element, books:

<books
    xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
>

In this way, all elements within the books element have access to these tag libraries.

As an alternative, you can scope the namespaces:

<books>
...
    <jsp:useBean xmlns:jsp="http://java.sun.com/JSP/Page"
                        id="bookDB"
                         class="database.BookDB"
                         scope="page">
         <jsp:setProperty name="bookDB"
                         property="database" value="${bookDBAO}" />
    </jsp:useBean>
    <c:forEach xmlns:c="http://java.sun.com/jsp/jstl/core"
                    var="book" begin="0" items="${bookDB.books}">
                    ...
    </c:forEach>
</books>

In this way, the tag library referenced by the jsp prefix is available only to the jsp:useBean element and its subelements. Similarly, the tag library referenced by the c prefix is only available to the c:forEach element.

Scoping the namespaces also allows you to override the prefix. For example, in another part of the page, you could bind the c prefix to a different namespace or tag library. In contrast, the jsp prefix must always be bound to http://java.sun.com/JSP/Page, the JSP namespace.