How do I access a JSTL variable in a scriptlet?
Author: Deron Eriksson
Description: This Java tutorial describes how to access a JSTL variable in a scriptlet.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
JSTLSW variables are actually attributes, and by default are scoped at the page context level. As a result, if you need to access a JSTL variable value in a scriptletS, you can do so by calling the getAttribute() method on the appropriately scoped object (usually pageContext and request). We can see examples of this below. First, we create a JSTL variable called "myTest" with a value of "testValue". We display this value using the JSTL c:out tag and then in a scriptlet by calling getAttribute on the pageContext object with "myTest" as the String parameter. After this, we perform another example with the "anotherTest" variable, but this time we scope it to the request. We display its value using the JSTL c:out tag and then in a scriptlet by calling getAttribute on the request object with "anotherTest" as the String parameter. example.jsp<%@ page contentType="text/html; charset=ISO-8859-1" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <c:set var="myTest" value="testValue"/> #1:<c:out value="${myTest}" /> #2:<%=pageContext.getAttribute("myTest") %> <br/><br/> <c:set var="anotherTest" value="anotherValue" scope="request"/> #1:<c:out value="${anotherTest}" /> #2:<%=request.getAttribute("anotherTest") %> If we view the example.jsp page in a web browser, we see the expected results: As you can see, it's very easy to access a JSTL variable in a scriptlet. |