JSTL Expression Language accessing object properti

2019-03-28 03:18发布

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?

3条回答
戒情不戒烟
2楼-- · 2019-03-28 03:56

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.
查看更多
仙女界的扛把子
3楼-- · 2019-03-28 04:03

This should work:

public class MyClass {

    private int total = 100;

    public int getTotal() {
        return total;
    }

    ...
}
查看更多
闹够了就滚
4楼-- · 2019-03-28 04:09

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:

查看更多
登录 后发表回答