我今天正在学习一个教程,它让我摸不着头脑一个小时。考虑:
public class MyClass {
public int getTotal() {
amount = 100;
return amount;
}
}
以及 JSP 的摘录:
<p>Total: ${objectOfTypeMyClass.total}</p> //object instantiated elsewhere
代码中没有任何地方声明或使用过名为“total”的实例变量。整个项目(JSP 中除外)中唯一引用“total”一词的是方法 getTotal()。
因此,经过一些绝望的最后一搏实验后,表达式语言将 ${someObject.var} 计算为“调用 getVar() 方法>someObject 对象。
我花了一个多星期的时间学习这个冗长的教程,认为 ${someObject.var} 是在说“直接从 ${someObject.var} 获取保存的实例变量“var” >某个对象。
我是否一直都搞错了,我的观察是否正确,为了使用 EL 引用任何实例变量,您必须提供一个名为 getVarname() 的相应 getter 方法,其中“Varname”是实例变量的名称?
此外,EL 在这方面似乎不区分大小写。在上面的示例中,${objectOfTypeMyClass.total} 中的“total”全部为小写,而方法 getTotal() 的“T”大写。
既然我们这样做了,为什么我们不需要实例化变量“total”呢?我猜 EL 实际上并没有引用实例变量...只是一个 getter 方法?
什么给出了?
最佳答案
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?
这是正确的。 EL 遵守JavaBeans specification如 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".
不,它肯定不区分大小写。这是指定的行为。 ${bean.Total}
不会起作用。
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?
这是因为它应该遵守 Javabean 规范。
总而言之,阅读这两个规范,一切都会清楚:)
另请参阅:
关于methods - JSTL 表达式语言访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3772430/