Custom Tags

Custom tags are the user defined tags which helps in separating the business logic from the presentation of the web page.

Advantages of Custom Tags

  1. It eliminates the need of scriptlet tag.
  2. Separation of business logic from JSP.
  3. Re-usability.

A custom tag can either be an empty tag (without body) or a body tag (with body).

Syntax for Empty Custom Tag:

    <prefix:customTagName attr1=”attrName” attr2=”attrName2” ... />

Syntax for Custom body tag:

    <prefix:customTagName attr1=”attrName” attr2=”attrName2” ... >

Body of custom tag


Creating a Custom Tag

To create a custom tag, we need the following components:

  1. A Tag Handler class which should extend SimpleTagSupport class.
  2. A Tag Library Descriptor (TLD) file to define tags.
  3. A JSP file to use the custom tag defined in the TLD file.

1. Tag Handler Class

In our tag handler class, we are extending the SimpleTagSupport class and overriding its doTag() method.

We also need to use the object of JspWriter class to write data for the jsp file.

The getJspContext() method returns the current JsoContext object.

    package com.tutorialsduniya;
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.util.*;
    public class MyTagHandler extends SimpleTagSupport 
        public void doTag() throws JspException, IOException 
            JspWriter out = getJspContext().getOut();
                out.print("Date : ");
                out.print("Time : ");
            catch(Exception e)

2. Tag Library Descriptor (TLD) file

A Tag Library Descriptor file is an XML file that contains the information of each tag and Tag Handler classes. TLD file is used by the web container to validate the tags.

A TLD file must have the .tld extension and must be packaged in the /WEB-INF/ directory.


    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.1" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
        <short-name>Custom Tag</short-name>

3. JSP file

Our jsp file uses the taglib directive to use the tags defined in our tld file using uri of tld file.


    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="x" uri="WEB-INF/tlds/MyTagHandler" %>
    <!DOCTYPE html>