Attributes In Jsp Custom Tag

Along with accessing the body of the custom tag, you can also have the attributes which can be added to the custom tag. In order to define a attribute in the custom tag we need to have the below two entries.

  • we need to define a property in the Tag Handler Class and have a setter method for it.
  • Define attribute tag inside the TLD File.

Lets add the attribute “message” to our custom tag, so our custom tag look like below.

<my:mytag message="Custom Attribute Message"></my:mytag>

Tag Handler Class (

Our MyCustomTag class act as a Tag Handler Class which extends the SimpleTagSupport class and we need to override doTag() method where we need to place the code which need to executed when our custom tag is encountered.

package com.javainterviewpoint;


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

public class MyCustomTag extends SimpleTagSupport 
    String message;
    public void setMessage(String message) {
        this.message = message;
    StringWriter sw = new StringWriter();
    public void doTag()throws IOException,JspException
        JspWriter out = getJspContext().getOut();
        out.print("<h3>"+message+" : "+sw.toString()+" : Text Appended!!!</h3>");

In the above code we have a setter for message property which will be the attribute passed from our custom tag and we are getting the body text of the custom tag as well and appending all together.

TLD File (custom.tld)

Our TLD file should be placed in the location “<<Project Name>>/WebContent/WEB-INF/custom.tld” and our file should always end with .tld extension. we have added a new tag <attribute> in our tld file whose name will be used in the custom tag(JSP page).

     <short-name>My Custom Tag</short-name>

JSP Page

We have created our custom tag mytag which we will be using here. Using the taglib directive we need to add the uri of our tld file and prefix to call our tag. So now we can call our custom tag by calling <my:mytag> . We have added the attribute “message” to our custom tag.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@taglib uri="/WEB-INF/custom.tld" prefix="my" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        <my:mytag message="Custom Attribute Message">Body of Custom Tag</my:mytag>

Once we run the above jsp page we will get the below output

Custom Attribute Message : Body of Custom Tag : Text Appended!!!

Leave a Reply

Your email address will not be published. Required fields are marked *