Simone Buzzi
Simone Buzzi

Reputation: 76

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:

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

How can I write a

<s:parameter value="...

and a

<s:if test="..

that use these data?

Upvotes: 0

Views: 514

Answers (2)

Roman C
Roman C

Reputation: 1

You can do this by setting action property and provide getter method.

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

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

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

Upvotes: 0

Simone Buzzi
Simone Buzzi

Reputation: 76

I solved adding

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

,after a lot of seach, to my struts.xml. I think that these constants are not well documented. Where could I find them in the apache struts website?

Upvotes: 1

Related Questions