简体   繁体   English

在OGNL Struts 2中调用单例方法

[英]Call a singleton method in OGNL Struts 2

I need to access a method of a singleton class to obtain a parameter 我需要访问单例类的方法来获取参数

The prototype of the call from Java code is: Java代码调用的原型是:

SosConstant.getInstance().getParameter("type");

I have a set of parameters that modify the view, so I need to access these data directly from the JSP 我有一组修改视图的参数,因此我需要直接从JSP访问这些数据。

How can I write a 我该怎么写

<s:parameter value="...

and a 和一个

<s:if test="..

that use these data? 使用这些数据?

I solved adding 我解决了添加

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

,after a lot of seach, to my struts.xml. 经过大量搜索后,转到我的struts.xml。 I think that these constants are not well documented. 我认为这些常量没有得到很好的记录。 Where could I find them in the apache struts website? 我可以在apache struts网站上找到它们吗?

You can do this by setting action property and provide getter method. 您可以通过设置action属性并提供getter方法来做到这一点。

private Object type; 

public Object getType(){
  return type;
}

in the action or other initialization method 在动作或其他初始化方法中

type = SosConstant.getInstance().getParameter("type"); 

then in JSP you can access it as usual 然后在JSP中您可以照常访问它

<s:property value="type"/>

or 要么

<s:if test="type == 'some type'">
...
</s:if> 

OGNL has a syntax that allows to call a static method, but it's prohibited for the security reasons, so by default this setting is turned off. OGNL具有允许调用静态方法的语法,但出于安全原因而被禁止,因此默认情况下此设置为关闭状态。 To get the instance of any object you need either create that object (that is not possible in your case) or use another object that returns the instance. 要获取任何对象的实例,您需要创建该对象(在您的情况下是不可能的)或使用另一个返回该实例的对象。 The action object instance is most suitable for this purpose. 动作对象实例最适合此目的。 All you need is create a method that returns an instance of the object (singleton in your case). 您所需要做的就是创建一个返回对象实例的方法(在您的情况下为单例)。

public SosConstant getSosConstant(){
  return SosConstant.getInstance();
}

then you can use it in JSP like 然后您可以在JSP中使用它,例如

<s:property value="sosConstant.getParameter('type')"/>

or 要么

<s:if test="sosConstant.getParameter('type') == 'some type'">
...
</s:if> 

Just one step around this but it's the same thing in OGNL. 只是迈出了一步,但在OGNL中却是一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM