JSP Taglib Directive

taglib Directive:

The JSP API’s allows us to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behaviour.

The taglib directive declares that our JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.

The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags.

In the custom tag section we will use this tag so it will be better to learn it in custom tag.

The taglib directive follows the following syntax:

<%@ taglib uri="uri" prefix="prefixOfTag">

 

Prefix is added to custom tag name.

Each library used in a page needs its own taglib

directive with unique prefix.

 

<%@ taglib prefix = “pre” uri = “randomName” %>

URI is a unique identifier in tag library descriptor(TLD).

It’s a unique name for taglib the TLD describe.

 

Let’s see an example with parameters action tag which comes in handy.

We have two JSP’s (action.jsp & output.jsp)

We have used declaration tag with scriplet for setting values with session object. Since scriplet is disregarded a long time we have used JSTL tag for doing this code.

action.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ include file="output.jsp" %>
<%!
String mobile="IPhone";
String company="Apple";
String place="US";
%>
<%
session.setAttribute("mo", mobile);
session.setAttribute("cm", company);
session.setAttribute("pl", place);
%>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="mo" value="IPhone" scope="session"/>
<c:set var="cm" value="Apple" scope="session"/>
<c:set var="pl" value="US" scope="session"/>
<%@ include file="output.jsp" %> 
</body>
</html>

output.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
<%=session.getAttribute("mo") %>
<%=session.getAttribute("cm") %>
<%=session.getAttribute("pl") %>
 
</body>
</html>

Now if we run the output.jsp we have the below output code:

taglibDirective

Posted on July 12, 2014 in Java Server Pages

Share the Story

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top