Every portlet WAR has a session associated with it. A portlet session is a java object. This session object can be used for sharing data between portlets and achieving IPC. So this article will explain IPC via portlet session.
To understand Portlet sessions, we have to understand session scope of the session object. There are two scopes – PORTLET_SCOPE and APPLICATION_SCOPE.
The data stored in the PortletSession of a portlet is not shared with any other portlets on the page, or anywhere else in the portal. This default behaviour is known as PORTLET_SCOPE. With the JSR-168(Portlet 1.0) portlet specification, concept of APPLICATION_SCOPE was introduced, and is available in its successor JSR-286(Portlet 2.0) which gives data access to all the portlets of the same WAR.
Let’s see the snippets:
Portlet 1: Setting Attributes:
PortletSession portletSession = renderRequest.getPortletSession();
// Application Scope
portletSession.setAttribute("appParam","I’m Sample App Scope Param Value", PortletSession.APPLICATION_SCOPE);
// Portlet Scope
portletSession.setAttribute("portletParam"," I’m Sample Portlet Scope Param Value ", PortletSession.PORTLET_SCOPE);
Portlet 2: Fetching Attributes:
PortletSession portletSession = renderRequest.getPortletSession();
// Application Scope
String appParam = (String) session.getAttribute("appParam", PortletSession.APPLICATION_SCOPE);
// Portlet Scope
String portletParam = (String) session.getAttribute("portletParam", PortletSession.PORTLET_SCOPE);
Portlet session attributes can be removed also, using the following:
PortletSession portletSession = renderRequest.getPortletSession();
portletSession .removeAttribute("appParam")
portletSession .removeAttribute("portletParam ", PortletSession.PORTLET_SCOPE);
Please note that both methods are interchangeable.
Liferay further provide feature for sharing portlet session attributes with portlet from other WARs. For achieving the same, we have to set <private-session-attributes> to false in liferay-portlet.xml.
That’s all for today. Thanks for reading and have a nice day.