I was following a tutorial today that had me scratching my head for an hour. Consider:
public class MyClass {
public int getTotal() {
amount = 100;
return amount;
}
}
and an excerpt from a JSP:
<p>Total: ${objectOfTypeMyClass.total}</p> //object instantiated elsewhere
Nowhere in the code was an instance variable named "total" ever declared or used. The only reference to the word "total" in the whole project (other than in the JSP) was the method getTotal().
So after some desperate last-ditch experimentation, it appears that Expression Language evaluates ${someObject.var} as "call the getVar() method of the someObject object.
I worked with this long tutorial for over a week thinking that ${someObject.var} was saying "directly fetch the saved instance variable "var" from someObject.
Did I have it wrong the whole time and is my observation correct that in order to reference any instance variable using EL, you have to provide a corresponding getter method named getVarname() where "Varname" is the name of the instance variable?
Also, EL seems to be case-insensitive in this regard. In my example above, "total" in ${objectOfTypeMyClass.total} is all lowercase where the method getTotal() has a capital "T".
And while we're at it, why don't we need to instantiate the variable "total"? I guess EL isn't actually referencing an instance variable...just a getter method?
What gives?
The
.
inobjectOfTypeMyClass.total
is the JSTL EL Dot Operator. It can do a few different things. Including:map.key
accessed a value frommap
stored underkey
. orobject.property
accessesproperty
fromobject
using "JavaBeans" conventions.This should work:
That's correct. EL adheres the JavaBeans specification as described in the EL specification.
No, it's certainly not case insensitive. It's specified behaviour.
${bean.Total}
would not have worked.It's because it's supposed to adhere the Javabean specification.
All with all, read the both specifications and everything will be clear :)
See also: