Creating Custom Tag In JSP

A Custom Tag is a user-defined JSP language element. When a JSP page containing a Custom Tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The web container then invokes those operations when the JSP page's servlet is executed.

JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would the built-in tags. Custom Tags are distributed in a tag library, that defines a set of related Custom Tags and contains the objects that implement the tags. The object that implements a Custom Tag is called a tag handler.

Let's do a demo: Create a "<today>" tag using the
following:

  1. To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us create a MyTagHandler.java class file inside the user package and write the following code in that class:

    image1.gif

    The code above is simple, where the "doTag()" method just prints the current day and time.
     
  2. Right-click on "WEB-INF" then click on "Others" then under "web catagory" click on "Tag Library Descriptor" as in the following:

    image2.gif
     
  3. Click on "Next", then for the TLD Name provide "MyTag" as in the following:

    image3.gif
     
  4. Open the MyTag.tld file and enter the following code to create the Custom Tag:

    image4.gif
     
  5. Now it's time to use the above defined Custom Tag "Hello" in our JSP program as follows. Open Index.jsp and provide a reference to the tag library by writing the following code:

    <%@taglib uri="WEB-INF/tlds/Mytags.tld" prefix="m" %>

    image5.gif

    The preceding image shows the complete code of index.jsp.
     
  6. Run your index.jsp page. If everything goes fine then you will get the following output.

    image6.gif

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles