Thursday, May 28, 2009

Sharing Data Among Portlets

There are number of ways to share data among portlets. This article introduces all these techniques.

Using PortletSession: Any portlets that are located in a same WAR file can share data using PortletSession. The setAttribute and getAttribute methods needs to be called with scope argument set to PortletSession.APPLICATION_SCOPE in order to share data.

Public Render Parameters: The render parameters set from either in processAction method or in render URL are only accessible from the same portlet. JSR 286 introduces public render parameters to share navigational state across portlets even located in different WAR files. Using this parameters to share data avoids event phase as needed using event technique. The render parameters can be shared by just defining XML elements in portlet.xml.

* The public-render-parameter tag should declare the parameter at portlet application level.
* Each portlet must reference the defined parameter using supported-public-render-parameter tag.

Using Events: In addition to public render parameters, JSR 286 introduces events to share data. Unlike public render parameters, events allows to send payload as an object. In order to share data using events, an action phase should occur by user's action of either clicking on a link that is created with action URL or submitting a form whose action is created as action URL. Here are the key points to understand the flow.

* Both sender and receiver portlets should declare same event using event-definition element at application level in portlet.xml.
* The sender portlet should refer the event using supported-publishing-event at portlet level in portlet.xml.
* The receiver portlet should refer the event using supported-processing-event at portlet level in portlet.xml
* The action invocation should occur to sender portlet. During processAction method, it should create pay load object and call ActionResponse.setEvent method to publish event.
* The receiver portlet should define processEvent. In this method it can get event object from EventRequest object. This event object carries payload.