javajspstruts2ognlvaluestack

How can I put a bean object to sessionMap, and then retrieve its properties on jsp page using Struts 2 property tag


In login Action I am checking user authentication, and if it is validated, I am putting the user bean into sessionMap:

public String execute()
{
    if(userValid)  
        sessionMap.put("userBean", userBean); //userBean retrieved from DB
}

Now on the landing jsp, when trying to retrieve the session items:

<s:property value="#session.userBean.name" />

Obviously this would return an Object type, as I am storing it that way, so how can I type caste this to UserBean class.

I was expecting to get a solution for this on Google, but found it nowhere since this seems to be a basic implementation. So please let me know if there is any other way to implement this functionality using Struts2.


Solution

  • Obviously you can't cast it to UserBean class if the object is not the instance of that class. In the value attribute you have put a string "#session.userBean.name". Struts parse this string for OGNL expression and if it's a valid expression that returns a value, it will replace it with that value. The returned type is Object, but this type is determined by ValueStack implementation.

    Then property tag writes this object to the out. It uses toString() to convert the object to string. And if your object implements this method, then this value would be written.

    Looks like your expression returns an Object, which has instance type String, so it's already implemented this method.