You probably won’t (and shouldn’t) do calculations and logic from EL. Remember, a JSP is the View, and the View’s job is to render the response, not to make Big Important Decisions or do Big Processing. If you need real functionality, that’s normally the job of the Controller and Model. For lesser functionality, you’ve got custom tags (including the JSTL tags) and EL functions.
But... for little things, sometimes a little arithmetic or a simple boolean test might come in handy. So, with that perspective, here’s a look at the most useful EL artithmetic, relational, and logical operators.
Arithmetic (5)
Addition: | + |
Subtraction: | - |
Multiplication: | * |
Division: | / and div |
Remainder: | % and mod |
Logical (3)
AND: | && and and |
OR: | || and or |
NOT: | ! and not |
Don’t use EL reserved words as identifiers!
You can already see 11 of them on this page—the alternate “words” for the relational, logical and some arithmetic operators. But there are a few more:
true | a boolean literal |
false | the OTHER boolean literal |
null | It means... null |
instanceof | (this is reserved for “the future”) |
empty | an operator to see if something is null or empty (eg. ${empty A}) returns true if A is null or empty (you’ll see this in action a little later in the chapter) |
Relational (6)
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 equal to: | >= and ge |
Sharpen your pencil
Look at the servlet code, then figure out what prints next to each EL expression. You’ll have to guess in a few places, since we haven’t covered every possible rule. This exercise will help you figure out how EL behaves. Hint: EL is flexible and forgiving.
Given this servlet code:
String num = "2"; request.setAttribute("num", num); Integer i = new Integer(3); request.setAttribute("integer", i); java.util.ArrayList list = new java.util.ArrayList(); list.add("true"); list.add("false"); list.add("2"); list.add("10"); request.setAttribute("list", list);
What prints for each of these?
___________ |
|
___________ |
|
___________ |
|
___________ |
|
___________ |
|
___________ |
|
<jsp:useBean class="foo.Dog" id="myDog" > <jsp:setProperty name="myDog" property="name" value="${list[1]}" /> </jsp:useBean> | |
___________ |
|
___________ |
|
Sharpen your pencil
Given this servlet code:
String num = "2"; request.setAttribute("num", num); Integer i = new Integer(3); request.setAttribute("integer", i); java.util.ArrayList list = new java.util.ArrayList(); list.add("true"); list.add("false"); list.add("2"); list.add("10"); request.setAttribute("list", list);
What prints for each of these?