In this section of the tutorial, we'll learn how to work with variables in JSP expression language (EL). EL is a powerful scripting language that allows users to do almost anything they can do in regular programming language.
Variable are accessed as follows in EL:
${myvariable}
${myvar.property}
Simple variable (like strings or primitives) can be accessed as shown in first example, while the second example can be used to access properties of complex variable, e.g. Class objects. This is consistent with Java notation of accessing class variables.
Note that EL uses Java Beans –like structure for accessing properties. In our example, it will first look for public property named “property”, and if it's not found, it will look for a getter method “getProperty”. If none is found, an exception is thrown.
Another way of accessing variables is sing square brackets []:
${var[“propname”]}
${var[key]}
${var[1]}
In the first case, we access the property named “propname” inside variable var. In the other case, EL first evaluates the value of variable key and uses it to access property that is named as the evaluated value.
This syntax can be used to access contents of a map, list or array. For examples, if variable mylist is a Java list, we can access element in index 2 with expression
${mylist[2]}
Variable Scopes:
JSP specification defines 4 scopes in which variable can exist. These are:
- pageScope – variable that are declared and used within single JSP page
- requestScope – variables declared within single HTTP request
- sessionScope – variables declared within HTTP session
- applicationScope – variables declared within application
To access any of these scope, we can use .(dot) syntax as shown above. For example, to access a variable in session scope:
${sessionScope.myvar.myproperty}
Implicit Objects:
In addition to scopes, JSP specification also defines some implicit objects that can be accessed in any JSP page:
- param – maps a request parameter name to a single value
- paramValues – maps a request parameter name to an array of values
- header – maps a header name to a single value
- headerValues- maps a header name to an array of values
- cookie – maps a cookie name to a single value
- initParam – maps a context initialization parameter to s single value
The following code snippet shows how we can access a value of single HTTP header:
<jsp:element name="div"
<jsp:body>
Header value: ,${header["headerName"]}!
</jsp:body>
</jsp:element>
This concludes the discussion about JSP variable, which lays the foundation for JSP Expression Language. In the final two chapters, we will go into more details of EL and how to integrate servlets and JSP to work together.