JSP taglib directive Syntax with Example



The purpose of the taglib directive is to specify the location of the TLD and assign it a short alias (prefix) that distinguishes its tags on this page.
All JSP Examples at JSP Source Code Examples.

Syntax JSP Taglib directive

<%@ taglib prefix="tag prefix" uri="taglibURI" %>
where the two attributes are:
tag prefix - A name, unique on this page, used to identify tags from this library.
taglibURI - The URI of the tag library itself. This can be an absolute pathname beginning with / that is interpreted relative to the top of the Web application. Or, it can be a URL that acts as a symbolic name for the TLD. In this case, the name must be mapped to the actual TLD by means of an entry in the Web.xml file.

Example of JSP Taglib directive

In this example, we are using our tag named CustomTag. To use this tag we must specify the taglib directive so the container may get information about the tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="myprefix" uri="/WEB-INF/message.tld"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Custom Tag Example</title>
</head>
<body>
    <h3>Basic Example of a Custom Tag </h3>
    <myprefix:CustomTag />
</body>
</html>

The taglib Directive

The second line contains the taglib directive:
<%@ taglib prefix="myprefix" uri="../WEB-INF/message.tld"%> 
This directive must appear in the JSP page before any of the custom tags it refers to are used. The top of the page is a good place.

How to Use the Tag in the JSP Page

The rest of the Web page is traditional HTML, with the exception of the line on which the custom tag is specified:
<myprefix:CustomTag />
When customtag.jsp is first invoked, the JSP container uses information from the taglib directive to locate the tag library descriptor and to identify where its tags are used on this page.
All JSP Examples at JSP Source Code Examples

Comments