Tuesday, October 28, 2008

OGNL - Calling Static Methods and Fields - struts 2

Most of the time, we have used to declare system constants as static fields
of a class, and some time static methods are being involved. If we want to access this kind of field from a JSP page with struts 2 taglibs, we have tow methods. I have tow classes 'SystemConstants' and 'Utils' in my own application.

public class
SystemConstants{
// ............
public static final
SESSION_DATA = "sessionData";
// .........
}

Also I have a separate class called "SessionData" to keep the data needed for the entire session. Useful information needed to keep through out the session are stored in the "
SessionData".

public class
SessionData{

private User user ;

public setUser(User user){
this.user = user;
}

public User getUser(){
return this.user;
}

}
I have stored the SessionData object in the session object from an "Action" class of struts 2.
SessionData sd = new SessionData();
getServletRequest().getSession()
.setAttribute(SystemConstants.
SESSION_DATA, sd);

Now, I want to access the session object and the "
SESSION_DATA" static field from the jsp page. This is where the point comes. For this, we have tow methods.


Method one:
To access the static field ,
<s:set name="sdKey"
value="@com.axiohelix.pda.utils.SystemConstants@
SESSION_DATA"></s:set>

Then to access the session object
from the "ActionContext",
<s:set name="objSd" value="#session[#sdKey]"/>

Then we can access the fields and methods declared in the SessionData object.
<s:property value="#objSd.user.userName"/>

This is how, we access static methods
@
com.axiohelix.utils.Utils@getSessionId()

If our field or method will resole in the 'ValueStack' in advance, we can use the fallowing syntax to access relevants
Method tow:
@vs@
SESSION_DATA
@vs@getSessionId()

The SESSION_DATA static field is declared in the class 'SystemConstants' packaged at
'com.axiohelix.utils' and getSessionId() function is implemented within the Utils class packaged at 'com.axiohelix.utils'


5 comments:

  1. Great information, helped me a lot
    Thanx

    ReplyDelete
  2. Here it is..
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>

    ReplyDelete
  3. If you want to access static methods in your JSP using OGNL, then you have to add the following entry to your struts.xml file

    ReplyDelete
  4. Useful stuff. Thanks man !
    Razvan

    ReplyDelete

Share

Widgets