Custom Tags in JSP

Custom Tags in JSP with Examples

In this article, I am going to discuss Custom Tags in JSP with Examples. Please read our previous article where discussed JSP Actions: Tags, Syntax, and Examples. At the end of this article, you will understand the following pointers with examples that are related to JSP Custom Tags.

  1. What are Custom Tags in JSP?
  2. Why we need custom tags?
  3. How to create Custom Tags?
  4. Taglib Directives
  5. Attributes of Taglib Directives
  6. TLD (Tag Library Descriptor) files
  7. Features of Custom Tags in JSP
  8. Declaring Tag Libraries in JSP
  9. Types of tags
  10. Tags with Attributes
  11. Tags with a Body
  12. Tag Handler
  13. How to invoke Tag Handler?
  14. Tag Handler Methods and Attributes
  15. Custom Tags Examples in JSP
Custom Tags in JSP

In JSP, by utilizing the JSP events we can characterize present JSP page qualities, but we can’t utilize JSP orders to perform activities in the JSP pages. To perform activities in the event we use scripting components, at that point we need to give Java code inside the JSP pages. The primary subject of JSP action isn’t to permit Java code inside the JSP pages, to use Java code from JSP pages we need to wipe out scripting components and also we need to utilize custom activities. Also to take out scripting components from JSP pages we need to utilize activities. Custom activities are JSP activities that could be set up by the designers according to their application prerequisites. In JSP Technology, standard activities will be spoken to as a bunch of predefined labels are called Action Tags. Additionally, all the custom activities will be given as a bunch of client-characterized labels are called Custom Tags.

What are Custom Tags in JSP?

A custom tag may be a user-defined JSP language element. The JSP page contains a custom tag which is translated into a servlet, those tag is converted to operations on a tag handler. When the JSP page’s servlet is executed the web container then invokes those operations. The standard JSP tags simplify all JSP page development and maintenance. It provides a mechanism for encapsulating other sorts of dynamic functionality in custom tags. Some examples include operating on implicit objects, processing forms, accessing databases and other enterprise services like email and directories, and implementing flow control. Custom tags increase productivity because they will be reused in additional than one application. Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the objects that implement the tags. The object that implements a custom tag is named a tag handler.

Syntax: <prefix_Name : tag_Name>—–Body—–</prefix_Name>

Why we need custom tags?

The custom tag is useful because of its rich set of features. They are:

  1. They can be altered through properties passed from the calling page.
  2. They approach all the articles accessible to JSP pages.
  3. They can adjust the reaction produced by the calling page.
  4. They can speak with one another. You can make and instate a JavaBeans segment, make a variable that alludes to that bean in one tag, and afterward utilize the bean in another tag.
  5. They can settle inside each other, considering complex communications inside a JSP page.
How to create Custom Tags?

If we want to design custom tags in our JSP applications then we have to use the following 3 elements:

  1. JSP page with Taglib directives: It is used to make available the TLD files into the present JSP page on the basis of custom tags prefix names.
  2. TLD (Tag Library Descriptor) file: This tag provides the mapping between custom tag names and respective TagHandler classes.
  3. TagHandler class: It is a normal Java class that is able to provide the basic functionality for the custom tags.

Perform the following steps to create and use custom tags:

  1. When you use a custom tag in your JSP, write a tag handler class that will execute the functionality of the tag. A tag handler class implements one of three interfaces:
    1. servlet.jsp.tagext.BodyTag
    2. servlet.jsp.tagext.Tag
    3. servlet.jsp.tagext.SimpleTag
  2. The tag handler class is implemented as part of a tag library.
  3. Then, reference the tag library in your JSP source using the JSP <taglib> directive and include this directive at the top of your JSP source.
  4. Then write the tag library descriptor (TLD) which defines the tag library and provides additional information about each tag, such as the name of the tag handler class, attributes, and other information about the tags.
  5. Then refer to the TLD in your Web application deployment descriptor (web.xml).
  6. Use your custom tag in your JSP.
Internal Flow

At the point when the holder experiences a custom label compartment will get the custom tag and name and the separate prefix name at that point perceive a specific taglib order based on the prefix property estimation. Subsequent to perceiving taglib mandate holder will get URI property estimation, for example, the name and area of the TLD document then the holder will perceive the particular TLD record. Subsequent to getting the TLD document compartment will distinguish the name and area of TagHandler class based on the custom label name. At the point when the holder perceives the separate TagHandler .class record then the compartment will perform TagHandler class stacking, launch, and execute all the existence cycle techniques.

Taglib Directives

In the custom label plan, the main motivation behind taglib mandate is to make accessible the necessary TLD document into the present JSP page and to characterize prefix names to the custom labels. The JSP API permits you to characterize custom JSP labels that appear as though HTML or XML labels and a labeled library is a bunch of clients characterized labels that actualize custom conduct. The taglib mandate pronounces that your JSP page utilizes a bunch of custom labels, distinguishes the area of the library, and gives way to recognizing the custom labels on your JSP page.

Synatx: <%@taglib uri=”–” prefix=”–“%>

Attributes of Taglib Directives:
  1. Prefix: It is used to specify a prefix name to the custom tag, it will have page scope i.e. the specified prefix name is valid up to the present JSP page.
  2. Uri: It will take the name and location of the respective TLD file.
TLD (Tag Library Descriptor) files

In JSP innovation, activities are components that can make and access programming language articles and influence the yield stream. The JSP detail characterizes six standard activities that should be given by any grumbling JSP execution. Notwithstanding the standard activities, JSP version1.1 innovation bolsters the advancement of reusable modules called custom activities. A custom activity is conjured by utilizing a custom tag in a JSP page. A label library is an assortment of custom labels. The fundamental motivation behind the TLD record is to give the planning between custom label names and the individual TagHandler classes and it can deal with the portrayal of the custom label’s characteristics. To provide the mapping between custom tag names and the respective TagHandler class we have to use the following tags:

<taglib>
<jsp-version>jsp version </jsp-version>
<tlib-version>tld file version</tlib-version>
<short-name> tld file short name</short-name>
<description>description about tld file</description>
<tag>
<name>custom tag name</name>
<tag-class>fully classified name of TagHandler class</tag-class>
<body-content>jsp or empty</body-content>
<short-name> custom tag short name</short-name>
<description>description about custom tags</description>
</tag>
 -------------
</taglib>

A few instances of undertakings that can be performed by custom activities incorporate structure preparing, getting to data sets and other venture administrations, for example, email and indexes, and stream control. Prior to the accessibility of custom activities, JavaBeans parts related to Scriptlets were the main system for performing such handling. The weakness of utilizing this methodology is that it makes JSP pages more unpredictable and harder to keep up.

Custom activities ease this issue by bringing the advantages of another degree of componentization to JSP pages. Custom activities exemplify repeating errands so they can be reused across more than one application and increment profitability by empowering division of work between library designers and library clients. JSP label libraries are made by engineers who are capable of the Java programming language and master in getting to information and different administrations. JSP label libraries are utilized by Web Application originators who can zero in on introduction issues instead of being worried about how to get to data sets and other undertaking administrations.

Features of Custom Tags in JSP:
  1. They can be altered through properties passed from the calling page.
  2. They approach all the articles accessible to JSP pages.
  3. They can adjust the reaction produced by the calling page.
  4. They can speak with one another. You can make and instate a JavaBeans segment, make a variable that alludes to that bean in one tag, and afterward utilize the bean in another tag.
  5. They can settle inside each other, considering complex communications inside a JSP page.
Declaring Tag Libraries in JSP

You declare that a JSP page will utilize labels characterized in a label library by incorporating a taglib order in the page before any custom tag is utilized:

<%@taglib uri=”/tlt” prefix=”tlt” %>

The Uri credits allude to a URI that interestingly distinguishes the label library. This URI can be relative or total. In the event that it is relative it should be planned to a flat-out area in the taglib component of a Web Application sending descriptor, the design record related with Web applications created by the Java servlet and Java Server Pages details. The prefix characteristic characterizes the prefix that recognizes labels given by a given label library from those given by other label libraries.

Types of tags:
  1. JSP custom actions are expressed using XML syntax. They have a start tag and end tag, and possibly a body: <tlt:tag>body</tlt:tag>
  2. A tag with no-body can be expressed as follows: <tlt:tag/>
  3. The simple tag invokes an action that creates a greeting: <tlt:greeting/>
Tags with Attributes

The start tag or a custom activity can contain ascribes in the structure attr=”value”. Traits serve to redo the conduct of a label similarly as boundaries are utilized to influence the result of executing a strategy on an article. Label attributes can be set from at least one boundary in the solicitation object or from a String steady. The solitary kinds of characteristics that can be set from demand boundary esteems and String constants are those recorded beneath. When allocating qualities to filled attributes the worth should be a cluster; the standards just portrayed apply to the components.

Property TypeConversion on String Value
boolean or BooleanAs indicated in java.lang.Boolean.valueOf(String)
byte or ByteAs indicated in java.lang.Byte.valueOf(String)
char or CharacterAs indicated in java.lang.Character.valueOf(String)
double or DoubleAs indicated in java.lang.Double.valueOf(String)
int or IntegerAs indicated in java.lang.Integer.valueOf(String)
float or FloatAs indicated in java.lang.Float.valueOf(String)
long or LongAs indicated in java.lang.Long.valueOf(String)

An attribute value of the structure <%= scriptlet_expression %> is registered at demand time. The estimation of the articulation relies upon the sort of the characteristic’s worth, which is indicated in the item that executes the tag (called a label controller). Solicitation time articulations can be relegated to characteristics of any sort; no programmed transformations will be performed. The following tag has an attribute named date, which accepts a String value obtained by evaluating the variable today:

<tlt:greeting date=”<%= today %>/>

Tags with a Body

A tag can contain custom and center labels, scripting components, HTML text, and tag-subordinate body content between the beginning and end tag.

Example: <tlt:greeting><%=today%></tlt:greeting>

Choosing Between Passing Information as Attributes or Body

As demonstrated in the last two areas, it is conceivable to pass a given piece of information as a property of the tag or to the label’s body. As a rule, any information that utilization a basic string or can be created by assessing a basic articulation is best passed as a trait.

Tags that define Scripting Variables

A tag can characterize a variable that can be utilized in contents inside a page. The accompanying model outlines how to characterize and utilize a scripting variable that contains an article got back from a JNDI query.

<tlt:lookup id=”tx” type=”UserTransaction” name=”java:comp/UserTransaction”/><%tx.begin();%>

Defining Tags

To define a tag, you need to:

  1. Develop a tag handler and helper classes for the tag
  2. Declare the tag in a tag library descriptor
Tag Handler

In custom tag readiness, the fundamental reason for TagHandler class is to characterize the essential usefulness for the custom labels. To characterize TagHandler classes in custom labels planning JSP API has given some predefined libraries as javax.servlet.tagext paclage (tagext label expansion). A label overseer is an article conjured by a JSP holder to assess a custom tag during the execution of the JSP page that references the tag. Label overseer techniques are called by the JSP page execution class at different focuses during the assessment of the tag.

At the point when the beginning tag of a custom tag is experienced, the JSP page usage class calls strategies to introduce the suitable controller and afterward summons the overseer’s doStartTag technique. At the point when the custom end tag is experienced, the overseer’s doEndTag strategy is conjured. Extra strategies are summoned in the middle of when a label controller needs to interface with the body of the tag.

How to invoke Tag Handler?

In order to provide a tag handler implementation, you must implement the methods that are invoked at various stages of processing the tag.

Following are the Tag Handler Methods:
Tag Handler TypeMethods
SimpledoStartTag, doEndTag, release
AttributesdoStartTag, doEndTag, set/getAttribute
Body, No InteractiondoStartTag, doEndTag, release
Body, InteractiondoStartTag, doEndTag, release, doInitBody, doAfterBody

A tag handler approaches an API that permits it to speak with the JSP page. The section highlight the API as the page setting object through which a label controller can admittance to the wide range of various understood items (solicitation, meeting, and application) available from a JSP page. Certain articles can have credits related to them. Such credits are gotten to utilizing the proper [set/get] Attribute strategy.

On the off chance that the tag is nested, a label controller likewise approaches the overseer (called the parent) related to the encasing tag. Label overseers should execute either the Tag or BodyTag interfaces. Interfaces can be utilized to take a current Java item and make it a label controller. For recently made overseers, you can utilize the TagSupport and BodyTagSupport classes as base classes.

Tag Handler Methods
  1. doStartTag: It is conjured when the beginning tag is experienced. It returns SKIP_BODY on the grounds that a basic tag has no-body.
  2. doEndTag: It is summoned when the end tag is experienced. It needs to restore EVAL_PAGE if the remainder of the page should be experienced; else it should restore SKIP_PAGE.
Tags with Attribute

For each label attribute, we should characterize a property and JavaBeans style get and set techniques in the label overseer. For instance, the label controller for the tag <tlt:twa attr1=”value1″> where value1 is of type AttributeClass, should contain the accompanying presentation and techniques:

private AttributeClass attr1;
setAttr1(SttributeClass ac){……….}
AttributeClass getAttr1(){……….}

Note that if yourattribute is named id, and your label controller acquires from the TagSupport class, you don’t have to characterize the property and set and get strategies on the grounds that these are as of now characterized by TagSupport.

A label trait whose worth is a String can name the quality of one of the understood items accessible to label controllers. A verifiable item trait would be gotten to bypassing the label quality incentive to the [set/get] Attribute strategy for the implied object. This is a decent method to pass scripting factors names to a label overseer where they are related with objects put away in the page setting.

Custom Tags Examples in JSP

In the below JSP Custom Tags Example, we have created a custom tag that prints the current date and time. Now create a TagHandler “MyTagHandler.java” where we are inheriting TagSupport class and overriding its method doStartTag(). The PageContext class then provides getOut() method that returns the instance of JspWriter class. Then the TLD files contain information on the tag and Tag Handler classes. It contains inside the WEB-INF directory. In index.jsp we are specifying the path of tld file directly. We have used taglib directives to use the tags defined in the tld file.

index.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>Action Guru JSP8</title>
</head>
<body>
 <%@ taglib uri="WEB-INF/mytags.tld" prefix="m"%>
 Current Date and Time is:
 <m:today />
</body>
</html>
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>  
<!DOCTYPE taglib  
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  
    "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
 <tlib-version>1.0</tlib-version>
 <jsp-version>1.2</jsp-version>
 <short-name>simple</short-name>
 <uri>http://tomcat.apache.org/example-taglib</uri>

 <tag>
  <name>today</name>
  <tag-class>Action.MyTagHandler</tag-class>
 </tag>
</taglib>  
MyTagHandler.java
package Action;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyTagHandler extends TagSupport {
 private static final long serialVersionUID = 1L;
 public int doStartTag() throws JspException {
  JspWriter out = pageContext.getOut();// returns the instance of JspWriter
  try {
   out.print(Calendar.getInstance().getTime());// printing date and time using JspWriter
  } catch (Exception e) {
   System.out.println(e);
  }
  return SKIP_BODY;// will not evaluate the body content of the tag
 }
}

Output

Custom Tags in JSP with Examples

In the next article, I am going to discuss Different Types of Tags and Their Life Cycle with Examples. Here, in this article, I try to explain Custom Tags in JSP with Examples. I hope you enjoy this Custom Tags in JSP with Examples article.

Leave a Reply

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