Struts 2:字段的 getter 和 setter 名称不正确/拼写错误 [英] Struts 2: Incorrect/misspelled getter and setter name of a field
问题描述
我在 Struts 2 modelbean 中将一个布尔变量声明为 isABooleanValue
,我可以通过在 jsp 中使用这个 modelbean.aBooleanValue
来查看该值.
I have declared a boolean variable as isABooleanValue
in the Struts 2 modelbean and I am able to see the value by using this modelbean.aBooleanValue
in jsp.
getter 看起来像这样
getter looks like this
public boolean isABooleanValue(){
return isABooleanValue;
}
setter 看起来像这样
setter looks like this
public void setABooleanValue(boolean isABooleanValue){
this.isABooleanValue=isABooleanValue;
}
Jsp 代码
谁能解释一下如何从值堆栈中访问不正确的变量名称.
can anyone explain how an incorrect variable name be accessed like this from value stack.
编辑
解决方案
在 JSP 中使用属性是基于指定的 Getter 方法.modelbean.aBooleanValue
调用在您的模型 Bean 中定义的 isABooleanValue()
方法,因此,不依赖于私有字段名称.
Using property in JSP is based on the Getter method specified. modelbean.aBooleanValue
calls the isABooleanValue()
method defined in your Model Bean, hence, not dependent on private field name.
更新:-虽然这似乎适用于较旧版本的 OGNL,但与 Struts2 捆绑在一起的 OGNL 3.0.11 版(OgnlRuntime)可能会导致当字段名称的 getter 和 setter 不相同时显示空白值.
Update:- Though this may seem to work in older version of OGNL but OGNL version 3.0.11 (OgnlRuntime) which is bundled with Struts2 may cause blank values be displayed when getter and setter of fields names are not same.
推荐答案
如前所述,Aleksandr M 变量名有一个 private
修饰符.它对 Struts OGNL 隐藏了变量.当 OGNL 对一个表达式求值时,它总是在寻找可用于该名称的对象访问器.其中它使用更适合的一个来获取被评估键的值.
As mentioned Aleksandr M the variable name has a private
modifier. It hides the variable from Struts OGNL. When OGNL is evaluating an expression it's always looking for the object accessors available for the name. Among them it uses one that better fit to get the value for the key being evaluated.
如果一个变量名有一个 public
访问器,它使用这个变量的名字.如果它是一个方法访问器,那么它会根据方法名称计算一个名称.
If a variable name has a public
accessor it is using the name of this variable. And if it's a method accessor, then it calculates a name from the methd name.
例如如果你有一个方法
public boolean isABooleanValue(){
return isABooleanValue;
}
具有aBooleanValue
和ABooleanValue
的名称可以被OGNL 访问.它返回什么并不重要,但它应该是一个 boolean
值.
a names with aBooleanValue
and ABooleanValue
could be accessed by OGNL. It doesn't matter what it returns but it should be a boolean
value.
不建议将此类方法映射到操作,因为您可能会通过 OGNL 调用或在序列化过程中遇到不必要的操作调用.
It's not recommended to map such methods to an action, because unnecessary actions calls you may encounter via OGNL calls or during serialization.
这篇关于Struts 2:字段的 getter 和 setter 名称不正确/拼写错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!