Custom Tags in JSP

In the previous article, we have seen the JSP Standard Tag Library in detail. In this article, we will cover Custom Tags in JSP.

We use JSTL to avoid Scriptlet Tags but sometimes this is not enough we need to perform some more operation. Thanks to JSP which is extendable and we can create Our own Custom Tags to perform such operation.

What is Custom Tags?

Custom Tags are user-defined tags in JSP. When JSP is translated into a Servlet, custom tags are converted into the class which takes action on the object i.e Tag handler. Then the web container then calls those operations and executes it. JSP is extendable which lets you create new tags. Let’s see the hierarchy first.

JspTag interface

This is the root of all the interfaces and classes used in Custom tags.

Tag interface

It is a subinterface of root JspTag that provides methods to perform the operation at the start and end of the tag. The following are the fields in Tag Interface. Every field is public static int.

  • EVAL_BODY_INCLUDE: It evaluates the content of the body.
  • EVAL_PAGE: it evaluates the JSP page content after the custom tag.
  • SKIP_BODY: it skips the content of the body.
  • SKIP_PAGE: it skips the JSP page content after the custom Tag.

Methods of Tag interface

  • public void setPageContext(PageContext pc): This method sets the object of pageContext.
  • public void setParent(Tag t): This method sets the tag Handler parent.
  • public Tag getParent(): This method returns the object of the parent Tag handler.
  • public int doStartTag(): This method is used to define business logic to be performed at the start of the tag.
  • public int doEndTag(): This method is used to define business logic to be performed at the end of the tag.
  • public void release(): This method is used to release the state of an object.

IterationTag interface

It is a sub Tag of Tag interface that provides an additional method to reevaluate the body. The field of Iteration Tag interface is:

  • public static int EVAL_BODY_AGAIN: It reevaluates the body content.

Method of IterationTag interface

  • public int doAfterBody(): This method reevaluates the content of the body if it returns EVAL_BODY_INCLUDE.

Tag Support class

It implements the IterationTag interface. It provides additional methods.

Create custom tags

To create custom tags we need the following things.

  • JSP Page: A JSP page is where we will be writing our custom tags.
  • TLD File: It is a Tag descriptor file where we will specify our tag name, tag handler class, and tag attributes.
  • Tag Handler class: It defines what is the function of our custom tags.

How to Write a custom tag in JSP?

Let’s see a simple example of writing our custom Tag.

In this example, we are creating a custom tag ‘hello’ that will display the message “Welcome to Codedec 🙂 !!!”. We will create the following three files

  • Custom_handler.java: For business logic.
  • mytldfile.tld: It contains information of tag and tag Handler.
  • custom_jsp.jsp: We will use the tag here.

Custom_Handler.java

package com.codedec;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class Custom_Handler extends TagSupport {

  @Override
  public int doStartTag() throws JspException {
    // TODO Auto-generated method stub
    JspWriter jspWriter = pageContext.getOut(); // create instance of
                          // JSPWriter.
    try {
      jspWriter.print("<h1>Welcome To Codedec :-)</h1>");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return SKIP_BODY;
  }

}

mytldfile.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>mytldfile</short-name>

  <tag>
    <name>hello</name>
    <tag-class>com.codedec.Custom_Handler</tag-class>
    <body-content>empty</body-content>
  </tag>
</taglib>

custom_jsp.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">
<%@ taglib prefix="a" uri="WEB-INF/mytldfile.tld"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <a:hello />
</body>
</html>

Output

Attributes in JSP Custom tags

We can define the attribute in the custom tags. We can define the attribute by defining the setter method of the class.

Let’s understand using the simple example of squaring a number. We will create three file

  • index.jsp
  • Custom_Handler.java
  • mytldfile.tld

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">
<%@ taglib uri="WEB-INF/mytldfile.tld" prefix="mytag" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Square of 25 is: <mytag:square number="25"></mytag:square>
</body>
</html>

Custom_Handler.java

package com.codedec;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class Custom_Handler extends TagSupport {
  private int number;

  public void setNumber(int number) {
    this.number = number;
  }

  @Override
  public int doStartTag() throws JspException {
    // TODO Auto-generated method stub
    JspWriter jspWriter = pageContext.getOut();
    try {
      jspWriter.print(number * number);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return SKIP_BODY;

  }
}

mytldfile.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>mytldfile</short-name>

  <tag>
    <name>square</name>
    <tag-class>com.codedec.Custom_Handler</tag-class>
    <attribute>
      <name>number</name>
      <required>true</required>
    </attribute>

  </tag>
</taglib>

Output

Advantages of Custom Tags

  • It is simple to understand.
  • It eliminates the need for a scriptlet tag.
  • It also separates the business logic from the JSP page.
  • We can use the same business logic again which leads to the reusability of code.

Thus, In this article, we have learned about JSP custom Tags with a simple example and with its advantages

In the next article of this tutorial, we will cover the Client Request in JSP. We will see what happens when the client requests a webpage to the server in JSP.