Dynamic Attributes in Tag File in JSP 2.0

As we know that we can develop custom tag library as a simple tag file in JSP 2.0 and these tag files can accept attributes from the invoking JSP page. But one drawback of this approach is that we need to declare all the attributes in the tag file. JSP 2.0 provides a feature called dynamic attributes by using which we need not declare the attributes in the tag file using the attribute directive.

1) File Name : firstPage.jsp

<%@ page contentType="text/html" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags/mytags" %>
<body bgcolor="white">
	<my:person Age="28" EmployeeId="74852" Name="Bruce Wayne"  />

2) File Name : person.tag

<%@ tag body-content="empty" dynamic-attributes="dynattrs" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<table border="1" width="30%" height="20%" style="background-color:#EFEFEF">
	<c:forEach items="${dynattrs}" var="a">

3) Output

NameBruce Wayne

In the file firstPage.jsp I invoke a custom tag named person with three attributes : employee id, age and name.

The file person.tag holds the code to handle the person tag invocation. In this file I use the tag directive to declare a page scope attribute named dynattrs. This attribute is a Map of all the attributes and attribute values passed from the JSP page tag invocation. Next, I iterate through each item of dynattrs using c:forEach jstl tag. The property: key returns the map key and the property : value returns the key’s value. I use Expression language syntax ${} to display each key and value stored in the map.

also read:

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!