Master java skills

JSP Taglib Directive

JSP allow us to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.

Taglib directive syntax

<%@ taglib uri = "uri" prefix = "prefixOfTag" >

Taglib directive example

Let’s assume the custlib tag library contains a tag called hello. If we want to use hello tag with a prefix custTag, our tag would be <custTag:hello> and it will be used in the JSP file as follows −

<%@ taglib uri = "http://www.example.com/custlib" prefix = "custTag" %>

<html>
   <body>
      <custTag:hello/>
   </body>
</html>

Steps to create custom tag

  1. Create a Tag Handler class. This will be a java class which will have the logic to be processed using custom tag
  2. Create TLD (Tag library descriptor) file and define tags inside it
  3. Create a jsp file and use the custom tag defined inside TLD file

Step 1. Create tag handler class

CustomTagHandler.java

Please note that this class must extend TagSupport class.

package com.javatrainingschool;

import java.io.IOException;
import java.util.Calendar;

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

public class CustomTagHandler extends TagSupport {

	public int doStartTag() throws JspException {
		
		JspWriter out = pageContext.getOut();
			try {
				out.print("Hello custom tag.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return SKIP_BODY;// skip body content of the tag
	}
}

Step 2. Create TLD file

Create a file called custTag.tld file inside WEB-INF folder

<taglib>
   <tlib-version>1.0</tlib-version>
   <jsp-version>2.0</jsp-version>
   <short-name>Example TLD</short-name>
   
   <tag>
      <name>Hello</name>
      <tag-class>com.javatrainingschool.CustomTagHandler</tag-class>
      <body-content>empty</body-content>
   </tag>
</taglib>

Step 3. Create jsp page

hello.jsp

<%@ taglib prefix = "myTag" uri = "WEB-INF/custTag.tld"%>

<html>
   <head>
      <title>A simple custom tag</title>
   </head>
   
   <body>
      <myTag:Hello/>
   </body>
</html>

Output: