Skip to main content

Implementing portlet messaging using WebSphere Studio Application Developer V5 and the Portal Toolkit V5

Sukumar Konduru (konduru@us.ibm.com), Advisory Software Engineer, IBM
Sukumar Konduru is an Advisory Software Engineer at the IBM Dallas, Developer Technical Support Center. He holds an M.S in Computer Science from the University of Houston. You can reach Sukumar at konduru@us.ibm.com .

Summary:  This article provides step-by-step instructions for creating a portlet application that includes portlet messaging. You see how to develop a portlet application, using IBM WebSphere Studio Application Developer Version 5 with the Portal Toolkit 5.0 plugin installed, and how to enable one portlet to send a message to a second portlet.

Date:  25 Feb 2004
Level:  Intermediate
Activity:  307 views

Introduction

IBM®WebSphere® Portal V5.0 is a J2EE application that runs on IBM WebSphere Application Server V5.0. WebSphere Portal lets users create pages and then customize a page to have multiple portlets on it. WebSphere Portal Versions 4.x and 5.x provide a portlet API which enables portlets, located on the same page, to communicate with each other. Also, using the API for messaging, portlets can share data. Therefore, you can use the portlet API to implement messaging to quickly and simply enable data sharing or communication among portlets within a single page.

The following banking example illustrates how portlets can use messaging. A page on a banking portal contains three portlets. Portlet 1, called Customer Number, provides an interface for a customer to submit his customer number. Upon receiving the number, portlet 1 acts as a message sending portlet. It assembles a message containing the customer number and sends it to the other two portlets on the page. Portlet 2, called Savings Account, registers to receive messages. When it receives the customer number from portlet 1, it displays the details of the customer's savings account. Checking Account portlet, or portlet 3, also registers to receive messages. It uses the customer number, which it receives from portlet 1, to display the customer's checking account details.

For more complex intra-portlet communication scenarios, such as sharing data across Web applications, consider using cooperative portlets instead of the API. See the Related articles for more information on cooperative portlets and its predecessor technology, C2A, or click-to-action. Inter-portlet communication is not yet part of the JSR 168 specification; however, it will likely be in the next version of the Java Portlet Specification.

The portlet application in this article has been tested on WebSphere Portal V5.

This article assumes that the reader knows how to deploy a portlet application into WebSphere Portal and how to customize a page to include portlets on it.


Generating a portlet application

This section demonstrates how to generate a portlet application using WebSphere Studio Application Developer (hereafter called Application Developer). The generated project contains two portlets: one for sending a message, and another for receiving the message.

  1. Open Application Developer and select File -> New -> Other... In the Select wizard, select Portlet Development on the left side and Portlet Application Project on the right side.
    Figure 1. Selecting the portlet project
    Selecting Portlet Project
  2. Click Next and enter the following values in the wizard titled Define the Portlet Project.

    Project name: Messaging Sample
    Create basic portlet: selected

    Figure 2. Defining the portlet project
    Define the Portlet Project
  3. Click Next and keep J2EE Level 1.3/WebSphere Portal 5.0 selected.
    Figure 3. Specifiying the J2EE settings age
    J2EE Settings Page
  4. Click Next and enter the following values.

    Application name: Messaging Sample Application
    Portlet name: Receiving Portlet
    Portlet title: Receiving Portlet
    Change Code generation options: Checked
    Class prefix: ReceivingPortlet
    Figure 4. Specifiying the portlet settings
    Portlet Settings
  5. Click Next and choose the following.

    Add message listener: checked
    Add message sender portlet sample checked

    Figure 5. Specifying event handling choices
    Event Handling
  6. Click on Finish. Application Developer generates the portlet project, shown in Figure 6. The main window shows the generated portlet.xml, and the J2EE Navigator shows the portlet project directory structure.
    Figure 6. portlet.xml
    portlet.xml

    Portal Toolkit generated this portlet application project containing two portlets: a source portlet, which can send a message, and a receiving portlet, which can consume the message.


Modifying the generated source portlet class

The name of the source portlet, which sends the message, is confusing; therefore, you change it in this section.

  1. Expand Java Source and select ReceivingPortletMessageSender.java. Right-click and select Rename.
    Figure 7. Renaming Source Portlet
    Renaming Source Portlet
  2. For the new name, type SendingPortlet. Keep Update references to the renamed element selected, and click Finish.
    Figure 8. Refactoring
    Refactoring

  3. Figure 9. Modified class
    Modified class
  4. Open the file SendingPortlet.java and change the string ReceivingPortletMessageSender, which is part of four constants, to MessageSender.

    Also, change ReceivingPortletMessageSenderView.jsp to SendingPortletView.jsp.

    After you make the changes, SendingPortlet.java should look like Listing 1.

  5. Save the modified file.
    Listing 1. SendingPortlet.java
    							
           package messaging_sample;
    
    import java.io.IOException;
    
    import org.apache.jetspeed.portlet.*;
    import org.apache.jetspeed.portlet.event.*;
    
    /**
     *
     * A simple portlet to test portlet messaging.
     *
     */
    public class SendingPortlet extends PortletAdapter implements ActionListener {
    
       public static final String ACTION     = "messaging_sample.MessageSenderAction";
       public static final String ACTION_URI = "messaging_sample.MessageSenderActionURI";
       public static final String TEXT       = "messaging_sample.MessageSenderText";
       public static final String SUBMIT     = "messaging_sample.MessageSenderSubmit";
    
      /**
      * @see org.apache.jetspeed.portlet.PortletAdapter#doView(PortletRequest, 
     PortletResponse)
     */
    public void doView(PortletRequest request, PortletResponse response) 
    		throws PortletException, IOException {
        PortletURI messageActionURI = response.createURI();
        messageActionURI.addAction(ACTION);
        request.setAttribute(ACTION_URI, messageActionURI.toString());
        // Invoke the JSP to render        		
        getPortletConfig().getContext().
    	   include("/messaging_sample/jsp/SendingPortletView.jsp", request, response);
       }
    
     /**
     * @see org.apache.jetspeed.portlet.event.ActionListener#actionPerformed(ActionEvent)
     */
     public void actionPerformed(ActionEvent event) throws PortletException {
    	if (ACTION.equals(event.getActionString()))
    		getPortletConfig().getContext().
    			send(null, new DefaultPortletMessage
    			((String)event.getRequest().getParameter(TEXT)));
      }
    
    }
    
      


Modifying the JSP included by the sending portlet

The name in the source JSP is also confusing; therefore, you change it in this section.

  1. Expand Web Content ->messaging_sample->jsp->html and select ReceivingPortletMessageSenderView.jsp. Right-click and select Rename.
    Figure 10. Renaming sender JSP
    Renaming sender JSP
  2. Enter SendingPortletView.jsp and click OK.
  3. In the Moving or Renaming files window, click No.
  4. Open SendingPortletView.jsp and select the source tab.
  5. Globally replace the text ReceivingPortletMessageSender with SendingPortlet .

    Tip: When you replace, make sure you do not add any trailing spaces for either the "Find" or "Replace With" values.

  6. In the <Label class... line, specify Customer Number: as the label string.

    After you make the changes, SendingPortletView.jsp should look like Listing 2.

  7. Save the modified file.
    Listing 2. SendingPortletView.jsp
    							
        
     <%@ page contentType="text/html" import="messaging_sample.*" %>
    <%@ taglib uri="/WEB-INF/tld/portlet.tld" prefix="portletAPI" %>
    <portletAPI:init/>
     
    <DIV style="margin: 6px">
    
    <H3 style="margin-bottom: 3px">Message sender sample</H3>
    This is a sample message sender page to test portlet messaging.<BR>
    The source file for this page is "/Web Content/messaging_sample/jsp/html/SendingPortletView.jsp".
    <DIV style="margin: 12px; margin-bottom: 36px">
    <% /******** Start of sample code ********/ %>
    
      <FORM method="POST" action="<%=portletRequest.getAttribute(SendingPortlet.ACTION_URI)%>">
        <LABEL class="wpsLabelText"   
             for="<portletAPI:encodeNamespace value='<%=SendingPortlet.TEXT%>'/>">
             Customer Number:</LABEL></BR>
        <INPUT class="wpsEditField" 
             name="<portletAPI:encodeNamespace value='<%=SendingPortlet.TEXT%>'/>" 
             type="text"/>
        <INPUT class="wpsButtonText" 
             name="<portletAPI:encodeNamespace value='<%=SendingPortlet.SUBMIT%>'/>" 
             value="Submit" type="submit"/>
      </FORM>
    
    <% /******** End of sample code *********/ %>
    </DIV>
    
    </DIV>    
       


Modifying the receiving portlet code

You need to store the received message in an object of type PortletSession. The stored message is retrieved from PortletSession, when the portlet is in view state, as described in the following sections.

You use the following code to store the message into the session.

event.getRequest().getPortletSession().setAttribute("message", messageText);

  1. Open the ReceivingPortlet.java and add this code in the if clause that checks for the type of message.

    After you make the changes, ReceivingPortlet.java should look like Listing 3.

  2. Save the modified file.
    Listing 3. messageReceived
    							
        public void messageReceived(MessageEvent event) throws PortletException {
         if( getPortletLog().isDebugEnabled() )
            getPortletLog().debug("MessageListener - messageReceived called");
         // MessageEvent handler
         PortletMessage msg = event.getMessage();
         // Add PortletMessage handler here
         if( msg instanceof DefaultPortletMessage ) {
            String messageText = ((DefaultPortletMessage)msg).getMessage();
            // Add DefaultPortletMessage handler here
            
         event.getRequest().getPortletSession().setAttribute("message",
                messageText); 	     
          }
    	   else {
    	      // Add general PortletMessage handler here
    	    }
    	}
    	


Modifying the receiving portlet JSP

In the previous section, you saw how to store the received message into an object of type PortletSession. This section shows how to display the message in the portlet titled ReceivingPortlet

.

  1. Add this code to ReceivingPortletView.jsp, right before the ending DIV element.
    The Customer Number is  <%= (String)portletRequest.getPortletSession().getAttribute("message") %> 

    After you make the changes, ReceivingPortletView.jsp should look like Listing 4.

  2. Save the modified file.
    Listing 4. ReceivingPortletView.jsp
    							
       
       <%@ page contentType="text/html" import="java.util.*, messaging_sample.*"%>
    <%@ taglib uri="/WEB-INF/tld/portlet.tld" prefix="portletAPI" %>
    <portletAPI:init/>
      
    <DIV style="margin: 6px">
    
    <H3 style="margin-bottom: 3px">Welcome!</H3>
    This is a sample <B>view mode</B> page. You have to 
    edit this page to customize it for your own use.<BR>
    The source file for this page is 
    "/Web Content/messaging_sample/jsp/html/ReceivingPortletView.jsp".
    
    The Customer Number is  <%= (String)portletRequest.getPortletSession().getAttribute("message") %>
    </DIV>
       


Modifying the deployment descriptors

Next, you need to modify the portlet deployment descriptor, portlet.xml, and the web application deployment descriptor, web.xml, to change the names and titles of the portlets and to reflect the updated portlet source class.

  1. Open portlet.xmland change the text Receiving Portlet (Message sender) to Sending Portlet globally. Change the name of the portlet in two places and the title of the portlet once.
  2. Open web.xml and portlet.xml and change the text ReceivingPortletMessageSender to SendingPortlet globally.

Exporting the WAR file

In the previous sections you generated a portlet application that comprises portlets that communicate with each other. You renamed file names and titles of portlets to reflect the function of what portlets do.

The generated code for SendingPortlet included an HTML form to let the user enter a message. Also it included code for sending a message using PortletContext.send() method.

You modified the genereated messageReceived method of ReceivingPortlet to store the received message into the PortletSession object; therefore, you modified the JSP to display the message when the portlet returns to view mode.

Now, you export the WAR so that you can deploy the portlet application into WebSphere Portal 5.0 to test the portlets.

  1. Select Messaging Sample. Right-click and select Export.
    Figure 11. Exporting
    Exporting
  2. Select WAR and click on Next.
    Figure 12. Selecting Type of Output File
    Selecting Type of Output File
  3. Enter the name of the exported WAR file, including the full path. Check Export source files so that you can package the source code into the exported WAR file. Click Finish.
    Figure 13. Entering Output File Name
    Entering Output File Name

Seeing the results

After you deploy the WAR file you can run the portlets to see the results.

  1. Customize a page to have both portlets as shown in the following figure.
    Figure 14. Customized Page
    Customized page
  2. Enter some value for the Customer Number into SendingPortlet, as shown in Figure 15.
    Figure 15. Sending Value
    Customized page
  3. Click Submit. You see the message text containing the Customer Number in the receiving portlet, as shown in the following figure.
    Figure 16. Sending Value
    Customized page

Conclusion

In this article, you saw how to use Application Developer and the Portal Toolkit to generate two portlets One of the portlets is enabled to send a message which is, in turn, consumed by the other portlet. Portlet messaging using the portlet API is a simple and useful way to enable portlets within a page to communicate with each other. If you require more complex message communications, such as communicating across pages, refer to the related articles about cooperative portlets and C2A, or click-to-action.


Resources

About the author

Sukumar Konduru is an Advisory Software Engineer at the IBM Dallas, Developer Technical Support Center. He holds an M.S in Computer Science from the University of Houston. You can reach Sukumar at konduru@us.ibm.com .

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=13641
ArticleTitle=Implementing portlet messaging using WebSphere Studio Application Developer V5 and the Portal Toolkit V5
publish-date=02252004
author1-email=konduru@us.ibm.com
author1-email-cc=

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers