JSP custom tag

How to create a custom tag in JSP?

Today one of my colleague approached me and asked he needs to create a custom JSP tag. I did some quick google search and tried it out and it worked. Just wanted to share how it’s done.

It’s simple and straight forward.

Say you want to create a custom tag named and want to use it like this

<ex:hello />

Before creating the TAG we have to create the tag handler like this,

package com.karthik;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class HelloTag extends SimpleTagSupport {

public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println(“Hello Custom Tag!”);
}
}

Above code has simple coding where doTag() method takes the current JspContext object using getJspContext() method and uses it to send “Hello Custom Tag!” to the current JspWriter object.

Let us compile above class and copy it in a directory available in environment variable CLASSPATH. Finally create following tag library file: <YOUR_PROJECT>\WebContent\WEB-INF\custom.tld.

<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.karthik.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

So, Now let’s try to test our newly created JSP custom tag by including it in a jsp page.

<%@ taglib prefix=”ex” uri=”WEB-INF/custom.tld”%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello/>
</body>
</html>

Now deploy your application and try accessing the jsp. You should see this result.

Hello Custom Tag!

Technology always excites me. Gangadhar, Thanks man.
Today I had some learning because of you my friend. This post is for you mate. Cheers 🙂

Happy Coding 🙂

Advertisements