Adding attributes to a custom tag

In this post, you will learn:

  • Why attributes are used in custom tags?
  • How to use attributes with a custom tag?

Role of attributes in a tag:

Sometimes a custom tag need additional information in order to generate contents. Such information is provided to the tags by the application programmers with the help of attributes.

Steps required to add attributes to a tag:

1. For each attribute which is to be supported by a tag, a data member is added to the Tag class.

2. A setter method is defined in the Tag class for each attribute.

3. In the TLD file, configuration of the attributes is added to the tag configuration with the help of <attribute> sub element of <tag>.

4. When the tag is used in the JSP, value of attributes is provided.

Following is a simple custom tag which receives user name as attribute and displays welcome message for the user.

The HelloTag class:

package com.techmentro.learningpad;

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

public class HelloTag extends TagSupport {

	//data member to store attribute value
	private String user;
	
	//setter method to set the value of attribute
	public void setUser(String user) {
		this.user = user;
	}
	
	//to display welcome message for the user
	public int doEndTag()
	{
		JspWriter out=pageContext.getOut();
		try
		{
		out.println("Welcome, "+user+"<br/>");
		}catch(Exception ex)
		{
			System.out.println(ex);
		}
		return EVAL_PAGE;
	}
	
}

The TLD file:


<taglib>
<uri>techmentro/tags</uri>

<jsp-version>2.1</jsp-version>
<tlib-version>1.0</tlib-version>

<tag>
<name>hello</name>
<tag-class>com.techmentro.learningpad.HelloTag</tag-class>
<attribute>
<name>user</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

Note that the value of <rtexprvalue> attribute is set to true in the configuration which means that its value can be set using the expression tag in JSP.

The index.html page:

<form action="home.jsp">
Name <input type="text" name="name"><br/>
<input type="submit" value="submit">
</form>

The home.jsp:

<%@ taglib uri="techmentro/tags" prefix="tm" %>

<%
String uname=request.getParameter("name");
%>

<tm:hello user="<%=uname %>"/>

Output:

What ever name is entered by the user in the input form, is presented by the custom tag as follows: Welcome, UserName


Its time to recap the main concepts:

  1. Attributes are used by custom tags to receive input from the JSP.
  2. A tag can support any number of attributes.
  3. For each attribute a data member and setter method need to be added to the Tag class.
  4. Configuration of each attribute need to be added to the tag configuration in the TLD file.

Example Source Code

  • zip helloTag
    File size: 7 KB Downloads: 159
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

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