Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL Expression Language accessing object properties

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?

like image 465
ChrisM Avatar asked Sep 22 '10 18:09

ChrisM


2 Answers

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?

That's correct. EL adheres the JavaBeans specification as described in the EL specification.

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".

No, it's certainly not case insensitive. It's specified behaviour. ${bean.Total} would not have worked.

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?

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:

  • What are the advantages of Javabeans?
like image 154
BalusC Avatar answered Nov 24 '22 04:11

BalusC


The . in objectOfTypeMyClass.total is the JSTL EL Dot Operator. It can do a few different things. Including:

  1. map.key accessed a value from map stored under key. or
  2. object.property accesses property from object using "JavaBeans" conventions.
like image 33
Mark Bolusmjak Avatar answered Nov 24 '22 04:11

Mark Bolusmjak