In the previous sections, we briefly saw a few operators being used within EL expressions: the addition (+) operator, and even a glimpse of the ternary (?) operator.
In actuality, there are quite a number of operators that can be used within EL expressions. We'll start by looking at the arithmetic operators.
operatormeaning+addition-subtraction, unary minus*multiplication/ or divdivision% or modmodulus (remainder)
Examples:
<p>3 + 4 = ${3 + 4}</p>
<div>2 cubed is ${2 * 2 * 2}
The remainder of ${a} over ${b} is ${a mod b}
The relational operators are:
operatormeaningeq or ==equalsne or !=not equalslt or <less thanle or <=less than or equalsgt or >greater thange or >=greater than or equals
Examples:
<c:if test="${a == b}">${a} is equal to ${b}</c:if>
<p>True or false? ${a} is less than ${b} is ${a <
b}</p>
The logical operators are:
operatormeaningand or &&andor or ||ornot or !not
Arithmetic, Relational, Logical and Other Operators, Continued
Examples:
<c:if test="${a==b and c==d}">It’s true!</c:if>
<c:if test=”${not a}>It’s not true!</c:if>
A special operator lets us test if a scoped variable exists or if a collection has no elements, the empty operator:
operatormeaning empty
A unary operator that evaluates to true if:
- the operand is null, or
- the operand is an empty string, or
- the operand is an empty array, Map or List
Otherwise, evaluates to false.
Examples:
<c:if test=”${empty a}”>The scoped variable a is
empty!</c:if>
<c:if test=”${empty myCollection}”>The collection
is empty!</c:if>
<c:if test=”${not empty myCollection}”>The
collection is not empty!</c:if>
<c:if test=”${empty myString}”>The string is
empty!</c:if>
<c:if test=”${empty myBean.someProperty}”>The
property is empty!</c:if>
Another special operator is the ternary operator, also know as the conditional operator:
operatormeaning? An operator that evaluates to one of two conditional expressions. The format is:
conditional ? expression1 : expression2
If the conditional expression evaluates to true, then the value of the operation is expression1, else expression2.
Examples:
<p>The switch is ${switchState ? 'on' : 'off'}.</p>
<p>The value is ${(value % 2 == 1) ? 'odd' :
'even'}.</p>
<label>The value:</label> ${(empty value) ? 'N/A'
: value}
<p>There are ${thing.count} thing${(thing.count==1)
? '':'s'} available.</p>
The precedence of all these operators is as follows:
- [] .
- ()
- - (unary) not ! empty
- * / div % mod
- + - (binary)
- < lt > gt <= le => ge
- == eq != ne
- && and
- || or
- ? :
Parentheses can be used to affect evaluation precedence in the customary manner.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}