I am facing some problem in using EL in JSTL and not able to access Java Hash Map as I would like. I am aware that in EL the key, if Integer gets accessed as Long. I have following hash map definition that I am trying to access in JSTL -
Map<Long, Object> testMap = new HashMap<Long, Object>();
In JSP page, I need to check if the map contains a specific key or not. I attempt to do that by checking if not empty as following -
<c:if test='${ ! empty testMap[currObj.currVal]}'>
I also access the map's value for a key somewhere in the code like below -
<c:if test='${ testMapMap[5].data == 'something'}'>
Now the problem -
If i define my map above as <Integer, Object>
then the first c:if works but second fails (as the second tries to access it as Long). However, if I define my map above as <Long, Object>
the first if check always fails as it always recognizes it as empty but the second if statement where I check for the value works.
Is there any good way to make sure I access HashMap for both the if statements correctly? I will appreciate opinions.
What is
currObj
? Can you redefine itscurrVal
member as aLong
(orlong
)?A numeric literal (matching the
IntegerLiteral
production in the EL syntax) will be represented as aLong
. The expressioncurrObj.currVal
evaluates to anInteger
. ALong
neverequals()
anInteger
, so one expression must result in a different type.Essentially, what you need is an explicit type conversion. Nothing like this is built into EL, but you could create a custom EL function to do it for you. This is a static function that you implement in Java, then describe in a TLD. Another answer of mine gives an example of the packaging. Here's what the function and its usage could look like in your case.
The TLD would look like this:
In your JSP:
The JSP engine takes care of the necessary type coercion (from the
Integer
result ofcurrVal
to theLong
required by thetoLong()
method. Your method is there simply to indicate the required type; without it, the JSP engine sees the (erased) type of the argument oftestMap.get(Object)
, and doesn't see the need to perform any coercion sinceInteger
is-anObject
.