在Struts2中使用OGNL访问静态变量

时间:2011-08-02 02:17:50

标签: java-ee struts2 ognl

美好的一天!

我正在阅读Manning的struts2书,其中一个主题是使用OGNL使用语法@[fullClassName]@[property or methodCall]

访问静态变量

所以我在我的程序上尝试了它,我的代码如下:

BEAN:

public class ContactsBean {

    private static int count = 1;
    //getter and setter
}

ACTION:

private ContactsBean contacts;
//getters and setters

JSP:

   <s:property value="@com.demo.bean.ContactsBean@count" />

or
    <s:property value="@vs@count" />  //valuestack method

但它不起作用。我错过了什么吗? 谢谢。

4 个答案:

答案 0 :(得分:13)

  

@see OGNL Basics : Accessing static properties

BEAN

public class ContactsBean {
    private static int count = 1; 

    // static getter
    // setter
}

<s:property value="@com.demo.bean.ContactsBean@getCount()" />

其他案例

public class ContactsBean {
    public static final int SCALE = 50;
}

<s:property value="@com.demo.bean.ContactsBean@SCALE" />

答案 1 :(得分:3)

Apache Struts 2文档 - struts.properties http://struts.apache.org/2.0.14/docs/strutsproperties.html

要启用静态方法访问/调用,请在基础包中的struts.properties文件中设置Struts2常量:

struts.ognl.allowStaticMethodAccess=true 

..或者我相信你可以在struts.xml中将它设置为

<constant name="struts.ognl.allowStaticMethodAccess" value="true"/> 

答案 2 :(得分:0)

如果我们在struts.xml中提到以下条目

,它的工作正常
  <constant name="struts.ognl.allowStaticMethodAccess" value="true"/> 

答案 3 :(得分:0)

正如struts 2(2.3.20)的新版本中所提到的,这个(struts.ognl.allowStaticMethodAccess)将很快从struts中删除。

请查看Struts 2 refactoring code to avoid OGNL static method access,了解如何在新版本中使用此功能。