JSP Tutorial

Developing custom tags

Developing custom tags:

  1. Decide which tag to be used along with prefix or short name, tag name and attribute names if required.
  2. While we are choosing prefix it should not belongs to JSP, javax, javaw and java.
  3. After developing a custom tag one must specify the details about tag in a predefined file called tld (Tag Library Descriptor) file.
  4. tld file contains declarative details about custom tags.
  5. After developing tld file keep it into either WEB-INF folder directly or keep it into a separate folder called tlds folder and it in turns present into WEB-INF.
  6. Whenever we make a request to a JSP page where we are using custom tag will give location of tld file.
  7. The tld file gives information about tag handler class (JavaBeans class) in which we develop the arithmetic logic or business logic for the custom tag.

Syntax for specifying the location of tld files:

<% taglib uri = "location of tld file" 
          prefix = "prefix or short name of custom tag" %>

For example:

<% taglib uri = "/WEB-INF/tlds/x.tld" prefix = "database" %>

Here, taglib is a directive used for given information regarding tld file and prefix or short name of custom tag.

Entries in tld file:

Every tld file gives declarative details about custom tags. The following structure gives information regarding prefix name, tag name, tag handler class name, attribute names, etc.

x.tld:

<taglib>
    <tlibversion>1.0</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>database</shortname>
    <tag>
        <name>display</name>
        <tagclass>MyPack.x</tagclass>
        <bodycontent>empty</bodycontent>
        <attribute>
            <name>username</name>
            <required>true</required>
            <rtexprvalue>false</rtexprvalue>
        </attribute>
    </tag>
</taglib>

If a tag contains any attributes we must used <attribute/> in tld file. <attribute/> tag contains the following entries:

Syntax:

<attribute>
    <name>......</name> -7  represents name of the attribute
    <required>......</required> -7  represents either true or false
    <rtexprvalue>......</rtexprvalue> -7  represents required text expression value
</attribute>

When we use true, the required attribute should name. This attribute should be used compulsorily. When it is false, it is optional to use.

If we pass the data at runtime to the rtexprvalue attribute, this attribute must be true otherwise it is false.