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:
<%@ variable (attribute="value")* %>
or
<@ 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
<%@ taglib prefix="print" tagdir="/WEB-INF/tags/" %> <html> <body bgcolor="white"> <print:varTag> ${testValue} </print:varTag> </body> </html>
varTag.jsp
<%@ 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.
also read: