Search code examples
javastruts2ognl

Struts 2: Incorrect/misspelled getter and setter name of a field


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 looks like this

public boolean isABooleanValue(){
     return isABooleanValue;
}

setter looks like this

public void setABooleanValue(boolean isABooleanValue){
     this.isABooleanValue=isABooleanValue;
}

Jsp code

<s:property value="modelbean.aBooleanValue" />

can anyone explain how an incorrect variable name be accessed like this from value stack.

Edit

Solution

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.

similar question

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.


Solution

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

    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.

    For example if you have a method

    public boolean isABooleanValue(){
         return isABooleanValue;
    }  
    

    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.

    It's not recommended to map such methods to an action, because unnecessary actions calls you may encounter via OGNL calls or during serialization.