JSTL Expression Language (EL)

JSTL Expression Language Overview:
The Expression Language or EL as it is known is used by
JSP developers to access and use application data without using java code. EL
was introduced in JSTL 1.0, but now is formally defined in JSP 2.0. In this
tutorial you will learn the following:
- Syntax and correct usage of EL
-
EL Expression and Operators
-
Implicit Objects
-
Common mistakes and pitfalls in using EL
EL Expressions :
EL expressions are always within the braces { ..... }
and prefixed with the $ sign, such as ${user.adress}. In EL we can write
${expr},
which is equivalent to the sciptlet <%= expr %>. EL expressions can be used
in template text or as tag attributes
The user name is ${user.name}
<c:out value = "${user.name}" />
However there are certain restriction regarding the use
of EL expressions and in the following case EL can't be used.
- In jsp:useBean
- In body of a tagdependent tag.
- When EL processing is disabled whether within the
deployment descriptor or by using the isELIgnored attribute of page
directive.
To use the attribute set in some scope :
Hello ${sessionScope.user.name}
or Hello ${user.name}
The first named variable in the expression is either an implicit object or an
attribute. If the first value is an attribute, it can be an attribute in any of
the four scopes: page, request, session or application. Of all the JSP implicit
objects (see the table) only pageContext is not a Map. It is a reference to the
pageContext object. If the first value, to the left of the dot operator is a map
then second value, to the right of the dot operator must be a map key.. If the
first value is a Java Bean, then second value must be a bean property.
For example if we have got something like: ${user.name},
then user must be either a map or a bean and name is a map key or
bean property.
The [ ] Operator:
The restriction with the EL dot ( . ) operator is that
it works only when the value on its right side is either a bean property or a
map key for the value on the left. The [ ] operator on the other hand provides
much flexibility as by using it we can have a List or an Array in addition to
Map and Bean on the left side. So thing on the right or rather inside the [ ]
operator can be - A key to some Map, a bean property or an index into some array
or list that is on the left side of the operator.
Example : Using [ ] operator
Let we set an array as an attribute in a servlet as -
.......... String [ ] bigFive = {"U.S.A", "Russia",
"France", "China","U.K"};
request.setAtribute{"bigFive", bigFive};
Now in a JSP having access to scope, we can write -
First one is ${bigFive[0]} and that will print U.S.A
EL Reserved Words:
Following words are EL keywords and hence must
not be used as identifiers:
and eq gt true instanceof
or ne le false empty
not lt ge null div mod
Type Coercion:
With the [ ] operator, we will only get an error if the
index, or the value inside [ ] can not be coerced to some valid value. For
example all of the following statements are correct:
The Big Five are : ${bigFive}
The first one is ${bigFive[0]}
The second one is ${bigFive["1"]}
EL Operators and
Precedence:
Arithmetic
Operators:
| Addition |
+ |
| Subtraction |
- |
| Multiplication |
* |
| Division |
/ and
div |
| Remainder |
% and mod |
Logical Operators:
| AND |
&& and and |
| OR |
|| and or |
| NOT |
! and not |
Relational Operators:
| Equals |
== and eq |
| Not equals |
!= and ne |
| Less than |
< and lt |
| Greater than |
> and gt |
| Less than or Equal to |
<= and le |
| Greater than or equla to |
>= and ge |
empty : empty operator is used to determine if a
value is null or empty.
Conditional Operator: A ? B : C. Evaluate
B or C, depending on
the result of the evaluation of A.
Operator Precedence: Following order of
precedence should be kept in mind while using EL operators.
[] .
() - Used to change
the precedence of operators.
- (unary)
not ! empty
* / div % mod
+ - (binary)
< > <= >= lt
gt le ge
== != eq ne
&& and
|| or
? :
Operator Usage Examples:
${4+3}
${item.cost * quantity}
Handling Null Values:
${4 + null} is evaluated to 4
${4 div null} is evaluated to Infinity
${4 % null} results in a runtime exception
${4 < null} is evaluated to false
${null == null } is true
${4 != null} is true
${true and null} is evaluated to false
${true or null} is evaluated to true
${not null} is true
${X && Y && Z} does not evaluate Z if Y is false
EL Implicit Objects:
| EL Implicit
Object |
Desciption |
| pageContext |
the PageContext
object |
| pageScope |
A map to attributes
in page scope |
| requestScope |
A map to attributes
in request scope |
| sessionScope |
A map to attributes
in session scope |
| applicationScope |
A map to attributes
in application scope |
| initParam |
A map for
initialization of context parameters |
| param |
A map from parameter
name to one value |
| paramValues |
A map from parameter
name to all values |
| header |
A map from header
name to one value |
| headerValues |
A map from header
name to all values |
| cookie |
A map from cookie
name to one Cookie |
Using EL Implicit Objects:
- To retrieve the request URI
- ${pageContext.request.requestURI}
- To retrieve some property of a session
attribute ${sessionScope.user.name}
- To get cookie
values
${cookie.nameOfCookie.valu}
- To get the value of Init
parameters
${initParam.nameOfInitParam}
Getting Nested Properties:
If the bean class Person had an attribute of type
Address that in turn has an attribute StreetName of type String. Assuming that
the attribute "person" is already been set in the scope and the bean
classes follows the formal style having getters and setters. Then to get the
street name printed we have to write -
<%= ((mypack.Person)
request.getAttribute("person")).getAddress().getStreetName() %>
EL makes it considerably easy -
<html><body> Street : ${person.address.StreetName}
</body></html>
The Person Bean:
package myPack;
public class Person
{
public String name;
public Address address;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
..... other public getters and setters methods .....
}
The Address Bean:
package myPack;
public class Address
{
public String Line1;
public String Line2;
public String StreetName;
public String HouseNo;
.....
public getters and setters for all bean attributes
......
}
Inside servlet's doPost() method where attribute are
being set-
myPack.Person p = new myPack.Person();
p.setName("John");
myPack.Address address = new myPack.Address();
address.setStreeName("M.G.Road");
p.setAddress(address);
.....
request.setAttribute("person",p);
RequestDispatcher rd = request.getRequestDispatcher("getter.jsp");
rd.forward(request, response);
In the JSP to get the StreetName we simply write ${person.address.StreetName}
Request Parameters and EL:
We should used the implicit object param when there is
only one parameter for that particular parameter name. Whenever there are more
than one parameter values for a parameter the parameterValue implicit object
should be used.
Let the HTML page is -
....
Name: <input type = text name = "username">
<br>Address Line 1 : <input type = "text" name =
"address">
<br>Address Line 2 : <input type = "text" name =
"address">
<br><input type = "submit" value = "Submit">
</form></body></html>
In JSP it should be processed like -
Name is ${param.username}
<br>Address Line 1: ${paramValues.address[0]}
<br>Address Line 2: ${paramValues.address[1]}
Using Custom Methods in EL:
Methods or functions can be used by same mechanism like
custom tags. Methods should be defined as public static in a public class. The
mapping of function name is also required inside a tag library descriptor (.tld)
file.
Let we want to have our own function that returns a
random number between 1 and 100. This function is defined as a static method as
follows -
package myPack;
public class RH
{
public static int
rh( )
{
return (int) ((Math.random() * 100) + 1);
}
}
Now we have to do the required mappings in the TLD file named mytld.tld
<function>
<name>rh</name>
<function-class>myPack.RH</function-class>
<function-signature>int rh( )</function-signature>
</function>
Now we can use the method in JSP as follows -
<%@ taglib prefix="my" uri="/mytld"%>
<html><body>
${my:rh()}
</body></html>
Getting Information from Request
To get host header -
Host :
${header.host} or ${header["host"]}
To get Http Request Method -
Request Mehtod : ${pageContext.request.method}
Disabling EL: Following declaration can be
used in JSP pages to deactivate the use of Expression Language.
<%@ page isELIgnored ="true|false" %>
Common Mistakes in using EL:
- Not using the curly braces
- Wrong usage of Implicit Objects
- Using Illegal characters
- Wrong handling of null values

|
Current Comments
2 comments so far (post your own) View All Comments Latest 10 Comments:you can use ${fn:containsIgnoreCase()}
Posted by Sivakarthick on Tuesday, 12.18.07 @ 13:29pm | #42809
Hi,
This is great tutorial, just one question how to check for equalIgnorecase in jstl for string comparision ?
Thanks,
Vinit
Posted by Vinit on Monday, 03.19.07 @ 19:11pm | #12190