liferay Using Portlet session


Example

This is one approach which has been there since JSR 168.It allows us to share attributes using portlet session.A portlet session can have different types of scopes:

  1. Portlet scope(attributes available only within portlet)
  2. Application scope(attributes available within whole application[war])

In order to use this approach,we do not need to make any entries in portlet configuration,as portlet session is readily available in portlet request:

PortletSession session = renderRequest.getPortletSession();
session.setAttribute("attribute-name","attribute-value", PortletSession.APPLICATION_SCOPE);

or

PortletSession session = renderRequest.getPortletSession();
session.setAttribute("attribute-name","attribute-value", PortletSession.PORTLET_SCOPE);

The attribute can only be retrieved from the respective scope only.Like for attribute set in portlet scope,we need to fetch it using

PortletSession session = renderRequest.getPortletSession();
String attributeValue = (String) session.getAttribute("attribute-name", PortletSession.PORTLET_SCOPE);

The major limitation of this approach is lack of sharing among other portlet,outside of application scope.In order to overcome this,there is liferay specific approach to add <private-session-attributes> to liferay-portlet.xml

    <private-session-attributes>false</private-session-attributes>
    <header-portlet-css>/css/main.css</header-portlet-css>
    <footer-portlet-javascript>/js/main.js</footer-portlet-javascript>
    <css-class-wrapper>{portlet-name}</css-class-wrapper>
</portlet>

for all portlets,where the attributes are set and retrieved.