JSP taglib Directive

This article is a series of JSP Tutorial. In this article, we will learn how to use JSP taglib directive with an 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.

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 path name 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 a entry in the Web.xml file.
For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as follows −

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.
Check out a complete example at JSP Custom Tag Development.

In this next article, we will learn How to Call a Java Class in JSP.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments