Relationship of HttpSession and PortletSession in context of SessionAttribute sharing

As portlet is based on top of servlet, so there could always be scenario where we need to introduceservlet in a portlet application and also there might be cases when we need to share session attributes betweenHttpSession and PortletSession.

We can always get attributes from HttpSession which has been set by PortletSession and vice versa.

In JSR168 Portlet sepc, PortletSession has two scopes APPLICATION_SCOPE and PORTLET_SCOPE.

session attribute which has been set using APPLICATION_SCOPE will be available to all the portlets in a Portlet Application.session attribute which has been set using PORTLET_SCOPE will only be available to that portlet in a Portlet Application.

sample code to get portlet session and setting/getting of session attribute with different scopes.

// get portletSession
PortletSession portletSession = request.getPortletSession();

// setting session attribute
portletSession.setAttribute("Key", "value", PortletSession.APPLICATION_SCOPE);
portletSession.setAttribute("Key", "value", PortletSession.PORTLET_SCOPE);

// getting session attribute

Note:- Default scope is PORTLET_SCOPE, if not specified.

If you set a session attribute with APPLICATION_SCOPE, you can get the same attribute from HttpSession.But if you set a session attribute with PORTLET_SCOPE, you CAN NOT get the same using HttpSession.

Reason:- when we set session attribute using PORTLET_SCOPE, portlet container internally create portlet id and add it to the session key, and this is the reason only that portlet can access the session attribute. And this is because it will not be available to HttpSession.

But adding of portlet id to session key doesn't happen with APPLICATION_SCOPE and that's the reason this session attribute with APPLICATION_SCOPE is available to HttpSession.

JSR 286 API provides a method to get portletId and you can get it usingrequest.getWindowId(). Once you get windowId/portletId, you can retrieve session attribute from Servlet which has been set in portlet using PORTLET_SCOPE.


Anonymous said...

Hi there ! Thanks for the helpful info... Its all in the scope :-)

nv.arunkumar said...

Thanks a lot buddy. It really made me to understand the scopes