Monday, January 12, 2009

Creating Custom Tag Library

JSTL is JSP Tag Library. It is the ability to define our own custom JSP tags.We design how JSP tags, its attribute and its body are intrepeted. They are called custom Tags.Thus a collection of Custom tags are called tag library. These tags can be used in any number of JSP files.they are re-usable component.It is a way that you can customise the JSP by defining own tags.

There are 4 main component in defining JSTL.
1) JSP Page
2) Tag Handler
3) Tag library descriptor
4) web.xml server configuration file

Tag Handler
-----------
The Tag handler is a Java Class. This Java Class says how to translate code into tag. It implements the javax.servlet.jsp.tagext.Tag interface. This class file will be in the same directory as of servlets and Java Beans This is generally done by extending the TagSupport or the BodyTagSupport class.

import javax.servlet.jsp.tagext.*;
public class Example1 extends TagSupport{

or

public class Example1 extends javax.servlet.jsp.tagext.TagSupport{


Tag Library descriptor
----------------------
The Tag library descriptor is an XML file which describes the name, class and attributes of the Tag Handler. Thus the JSP file will identify the class to the server and associate it with a particular tag name. This file will be of the extention .tld .This file contains some fixed information, an arbitrary short name for your library, a short description, and a series of tag descriptions. The URI of this tld file will be described in the JSP file with a prefix.

The JSP File
------------
The JSP file will import the tag library referencing the URL of the descriptor file. This defines a prefix to the tld , with which the tld will be accessed. We need to define the taglib directive in the top part of the JSP file.This will be of the form

<%@ taglib uri "=WEB-INF/lib/Example1.tld" prefix="Example" %>

The uri can be absolute or relative refering to the taglibrary descriptor.

Web.xml
-------
This is the file where the we tell the JSP file that where is our tld file is. The is the configuration file for the application to run.


No comments:

Post a Comment