Inter Portlet Communication (IPC) – Portlet Session in Liferay 7

Inter portlet communication is a mechanism to communicate between the portlets. This is a new feature brought up in JSR 286 (Java Specification Request). Communication between two portlets can a done using Portlet Session. Using this way, two different portlets in different pages can also communicate.

Let’s move step by step,

1. Create a new Liferay Plugin Project. Name it as “RC-Blog-IPC-Example”.

13-1

2. Now create two portlets “IPCSender” and “IPCReceiver”.

13-213-3

3. In liferay-portlet.xml file, for “IPC-Sender” portlet add the below few lines,

<private-session-attributes>false</private-session-attributes>
<requires-namespaced-parameters>false</requires-namespaced-parameters>

13-4

4. In view.jsp for “IPC Sender”, copy the below code,

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

<portlet:actionURL name="nameAction" var="actionUrl"></portlet:actionURL>

<form action="<%=actionUrl%>" method="POST">
What's your name: <input type="text" name="name">

<input type="submit" name="Submit" value="Submit">
</form>

13-5

5. In the “IPCSender” controller class, add the below code snippet,

@ProcessAction(name = "nameAction")
public void nameAction(ActionRequest request, ActionResponse response) {
 String name = ParamUtil.getString(request, "name", StringPool.BLANK);
 _log.info("IPC Sender name: " + name);

 PortletSession session = request.getPortletSession();
 session.setAttribute("username", name, PortletSession.APPLICATION_SCOPE); 
}

13-6

6. Till now we are done with the Sender class of the IPC. Now we need to work of the Receiver class, which will receive the “username” attribute from portlet session and process accordingly.

7. In the “IPCReceiver” controller class, replace the “doView” method with the below code,

public void doView(
 RenderRequest renderRequest, RenderResponse renderResponse)
 throws IOException, PortletException {

 PortletSession session = renderRequest.getPortletSession();
 String userName = (String) session.getAttribute("username", PortletSession.APPLICATION_SCOPE);
 if (userName != null) {
 renderRequest.setAttribute("userName", userName);
 }

 include(viewTemplate, renderRequest, renderResponse);
}

13-7

8. In the view.jsp for “IPC Receiver” portlet, paste the below code,

13-8

9. Now let build and deploy the portlet. Add both “IPC Sender” and “IPC Receiver” portlet in a page.

13-913-10

10. Now fill the textfield inside “IPC Sender” portlet and hit “Submit”.

13-11

The name entered in the “IPC Sender” portlet is now visible in “IPC Receiver” portlet.

 

Happy Coding… 🙂
Rupal Chatterjee
Associate Projects, Cognizant Technology Solutions
https://www.cognizant.com
Connect me on Google, Facebook