Bhavya Narula Bhavya Narula - 1 year ago 64
Java Question

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

In login

I am checking user authentication, and if it is validated, I am putting the user bean into

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

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

<s:property value="" />

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

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download