© Copyright Marcus Green 2007
7.3)Given a scenario, write EL code that uses the following operators: arithmetic operators, relational operators, and logical operators.
Part of the idea of JSP's is that business logic should not be mixed in with the presentation layer, however the EL supports arithmetic, relational and logical operators for when you just have to have logic within your JSP.
The EL supports the following arithmetic operators.
The following code illustrates how you can use the math operators of the EL
<html>
${2+2}
${3-1}
${2 * 2}
${10/2}
${10 div 2}
${10 %9}
${10 mod 9}
</html>
The output of this code is as follows
4 2 4 5.0 5.0 1 1
Rather strangely the EL math operators will accept strings that can be converted into numbers as parameters. Thus the following will evaluate to output 4.
${"2"+"2"}
|
|
EL math operators will accept strings that can be converted to numbers as parameters. |
The EL relational operators are very similar to those used in standard Java code except they come in bothy symbol and text versions. The are
Equality (== and eq)
Not Equals (!= and ne)
Less than (< and lt)
Greater than (> and gt)
Less than or equal (<= and le)
Greater than or equal (>= and ge)
Each of the following will result in an output of true
${1==1}
${1 ne 0}
${0 lt 1}
${1 gt 0}
${1 le 1}
${1 ge 1}
|
|
EL treats null as false |
The EL operators can be put to good use by embedding EL within the conditional operators of the JSTL. The following example demonstrates the use of the <c:if JSTL tag along with the EL greater than operator.
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<body>
<%
int[] i = {10};
request.setAttribute("age",i);
%>
<c:if test='${age[0] >1}'>
The value was greater than one
</c:if>
</html>
Note the use of core_rt in the uri for the JSTL tags. You may find example code that uses
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
But the conditional JSTL operators will not work with that URI.
EL treates attributes like variables and will overlook variables set in scriptlets. Thus the following will result in no output to the page (not even a null).
<%
int three = 3;
%>
${three}However the following will output the number 3
<%
request.setAttribute("three","3");
%>
${three}Perhaps even more surprising is the flexibility with which EL will manipulate variables that can represent numbers. Thus the following code will output the number 4.
<%
request.setAttribute("three","3");
%>
${three + 1}
Other Sources
According to Mikalai Zaikin
http://java.boot.by/wcd-guide/ch07s03.html