Variable Directive in JSP 2.0 Custom Tags

February 25, 2009

JSP

This tips explains how to use the variable directive in the custom tags in JSP 2.0. There is time when JSP page needs to
access the variable declared inside the Tag files. In the previous version we have to extend the tag library to declare the variables
and need the special handling for those variables. In JSP 2.0, it is done very easily using the variable directive. Syntax for the
variable directive is as follows:

1
	<%@ variable (attribute="value")* %>

or

1
	<@ variable attribute1="value1" attribute2="value2" ... %>

The following are the list of attributes in variable directive:

  • name-given
  • name-from-attribute
  • alias
  • variable-class
  • declare
  • scope
  • description

Look into the following example:

index.jsp

1
2
3
4
5
6
7
8
	<%@ taglib prefix="print" tagdir="/WEB-INF/tags/" %>
	<html>
		<body bgcolor="white">
			<print:varTag>
				${testValue}
			</print:varTag>
		</body>
	</html>

varTag.jsp

1
2
3
4
5
	<%@ variable name-given="testValue" %>
	<%
		jspContext.setAttribute("testValue", "testValue");
	%>
	<jsp:doBody/>

In the above example it declares one simple variable named testValue and it is access from the JSP page. This example is only very simple and the purpose is to explain how the variable directive is working. Like this you can declare asmany variables in the Tag Files and can be used in the JSP file. at the end of tag file is important to execute the tag body.

email

Comments

comments