Welcome!

IBM Cloud Authors: Yeshim Deniz, Elizabeth White, Pat Romanski, Liz McMillan, Stefan Bernbo

Related Topics: IBM Cloud

IBM Cloud: Article

Entering the Portlet Era

Entering the Portlet Era

Portals are Web sites that serve as a jumping-off point to information and applications on the Internet or from an intranet. To accommodate the aggregation and display of diverse content in a dynamic manner, a portal server must provide a framework that breaks the different portal components into pluggable portlets.

Each portlet is responsible for providing specific information and must therefore perform tasks like accessing content from its source (for example, a Web site, database, or e-mail server) and transforming the content so it can be rendered to the client most efficiently. The IBM WebSphere Portal for Multiplatforms Version 4.1 provides a framework of services to make the task of writing and managing portlets as easy as possible.

From a user's perspective, a portlet is a small window in the portal page that provides a specific service or information, for example, a calendar or news feed portlet. From an application development perspective, portlets are pluggable modules designed to run inside the portlet container of IBM WebSphere Portal 4.1.

Portlets are able to use the portal infrastructure to access user profile information, participate in window and action events, communicate with other portlets, access remote content, look up credentials, and store persistent data. To make performing these tasks very comfortable, the Portlet API provides standard interfaces for these functions.

Portlets and Servlets
All portlets are based on the abstract Portlet class, which is the central abstraction of the Portlet API.

Portlets are a special type of servlet, with properties that allow them to easily plug into and run in the portal server, plus various other features. They also have some natural restrictions: unlike servlets, portlets cannot forward requests, write arbitrary markup to the output stream, or send redirects and errors directly to browsers.

Generally, portlets are administered more dynamically than servlets. The following updates can be applied without having to start and restart the portal server:

  • Portlet applications consisting of several portlets can be installed and removed dynamically using the portal administration user interface.
  • The settings of a portlet can be changed on the fly by an administrator.
The portlet container relies on the J2EE architecture implemented by IBM WebSphere Application Server. Portlet developers benefit from this in a variety of ways:
  • The Portlet API leverages the well-known Servlet API, extending it where necessary.
  • Developers familiar with the Servlet API are able to instantly write portlets.
  • Developers can use existing tools to develop portlets and JSP.
  • Because portlets are part of the J2EE model, developers have a variety of options to combine J2EE-compliant technologies.
  • Developers can reuse simple existing servlets/JSP with little or no effort.
Portlets are packaged in WAR files similar to J2EE Web applications and are deployed like servlets. Like other servlets, portlets are defined to the application server using the Web application deployment descriptor (web.xml). This file defines the portlet's class file, the servlet mapping, and read-only initialization parameters.

In addition to the servlet descriptor, portlets must also provide a portlet deployment descriptor (portlet.xml) to define the portlet's capabilities for the portal server. This information includes configuration parameters specific to a particular portlet or portlet application, as well as general information that all portlets provide, such as what type of markup the portlet supports. The portal server uses this information to provide services for the portlet. For example, if a portlet registers its support for help and edit modes in the portlet deployment descriptor, the portal server will render icons to allow the user to invoke the portlet's help and edit pages.

Portlet Applications
Portlet applications provide the means to package a group of related portlets that share the same context. The context contains all resources, e.g., images, properties files, and classes. All portlets must be packaged as part of a portlet application.

Portlet applications provide no code on their own but form a logical group of portlets. Besides this more logical gain, portlets of the same portlet application share their session and can also exchange messages.

Let's Start
Before you can start developing a portlet, you need to set up a portlet development environment - and a runtime environment wouldn't be bad idea either. This environment can be set up on one machine, but for performance reasons, we suggest using two machines.

The Development Environment

  • JDK: WPS was compiled using JDK 1.3.0 (the JDK release shipped with IBM WebSphere Application Server 4.0.2).

  • Editor: You'll also want to install your favorite source-code and HTML editors.

  • J2EE Tools: Some example portlets in this article use JSP components to output markup to the user's client machine. IBM WebSphere Studio Application Developer is a good tool for editing these.

  • Libraries: The following Java archive (JAR) files are required: portlet-api.jar, wps.jar, wpsportlets.jar, j2ee.jar, and websphere.jar.

    The Runtime Environment On this machine you need to install IBM WebSphere Application Server 4.0.2, along with the latest set of patches. If you want this machine to have a fully functional version of WPS, you also need to install IBM DB2 Universal Database Version 7.2. These are prerequisite products for the developer release of WPS.

    Once you've installed and tested the software on both machines, you need to add references to the following JAR files, required for portlet development, to your development machine's CLASSPATH:

    • was_root/lib/app/portlet-api.jar
    • was_root/lib/app/wps.jar
    • was_root/lib/app/wpsportlets.jar
    • was_root/lib/j2ee.jar
    • was_root/lib/websphere.jar
    Note that was_root is the directory where IBM WebSphere Application Server is installed.

    Now that you have a complete development environment, it's time to do some portlet programming!

    The obligatory first portlet: HelloWorld! Listing 1 shows a simple portlet structure. HelloWorld, while not highly functional, shows the basic structure of a portlet. A simple portlet requires a single method, the service method. A portlet's service method is called when the portal is requesting that the portlet render its data. In this sample this code snippet contains the data:

    <p>Hello Portal! This is my first portlet!</p>

    Portlets packaged together in a single WAR file may share resources like images, JSP components, stylesheets, and other resources.

    You need to create a Web deployment descriptor, web.xml (see Listing 2), and a portlet deployment descriptor, portlet.xml (see Listing 3), and include these XML documents in your HelloWorld WAR file so you can package and run the HelloWorld sample.

    The portlet deployment descriptor describes the portlet application, each portlet in the application, and each portlet's title and capabilities. For a complete description of the portlet deployment descriptor, consult the IBM Portlet Development Guide (see Resources).

    Packaging the Portlet Application
    Now that you have the source code for the portlet and the portlet descriptor, you can package the pieces into a WAR file. Lay out the source code and portlet descriptor document in a directory structure such as the one shown below, which will make the building of the portlet and WAR file an easy process.

    helloworld.war
    __META-INF
    _ MANIFEST.MF
    __WEB-INF
     _ portlet.xml
     _ web.xml
     _
      __classes
       __com
        __ibm
         __wps
         __samples
          __helloworld
           HelloWorld.java

    Using this directory structure you can create a batch file that compiles the portlet and builds the associated WAR file. This batch file assumes the JDK CLASSPATH has been set up to point to the portal JAR files required to compile this portlet. For this example we named this batch file BuildEx1.bat and placed it in the HelloWorld directory. Be sure to modify line 2 of the batch file to point to the base directory where you stored your portlet files, as shown in the following code snippet. Note that some lines (here and in the following examples) have been split so they'll display.

    @echo off
    set bd=D:/HelloWorld
    javac -d
    %bd%/WEB-INF/classes
    %bd%/WEB-INF/classes/com/ibm/wps/samples/helloworld/HelloWorld.java
    jar -cf HelloWorld.war WEB-INF

    Running this batch file compiles the portlet and builds the WAR file. The next step is to run the portlet application on your runtime portal machine via the Install Portlet, as described in the WebSphere InfoCenter (see Resources).

    Stocks Portlet Sample
    To show some of the concepts and techniques associated with portlet development, we'll build a simple Stocks sample portlet, explaining each piece of the API we come across.

    In the VIEW mode the portlet shows the stock values, which can be configured in the EDIT mode.

    Portlet modes allow a portlet to display a different user interface, depending on the task required of the portlet. The following modes are provided by the Portlet API:

  • VIEW: When a portlet is initially constructed on the portal page for a user, it is displayed in its VIEW mode. This is the portlet's normal mode of operation.

  • HELP: If this mode is supported by a portlet, the portlet provides a help page for users to obtain more information about it.

  • EDIT: If this mode is supported by a portlet, it provides a page for users to customize the portlet for their own needs. For example, a portlet can provide a page for users to specify a location for obtaining local weather and events.

  • CONFIGURE: If this mode is supported by a portlet, it provides a page for portal administrators to configure the portlet for a user or a group of users.

    The Portlet API provides methods for the portlet to determine the current mode: One way would be to call PortletRequest.getMode() in the service() method. An easier way would be to extend the PortletAdapter class, which provides methods for each mode, e.g., doView(), which is called if the portlet should be rendered in the VIEW mode.

    This is similar to HttpServlet, which provides methods such as doPost(), in addition to the service() method.

    ...
    public void doView (PortletRequest request,
    PortletResponse response)
    throws PortletException, IOException
    {
    ...
    }
    ...

    What functionality do we provide in this example? In the VIEW mode, the portlet lists all user-defined stock symbols with their current values. To keep it simple, the current values will just be random numbers. To add some interaction, it's possible to hide or show a description for the stock symbols on request (by clicking a link). In the EDIT mode you're able to add new stock symbols by entering a name and a description. The user-defined stock symbols are listed here as well but without their value or description. Additionally, it's possible to delete the stock symbols. To keep it simple, we only provide the option to delete all stock symbols.

    How do we implement and prepare the portlet's basic functionality? First, we want to use JSP to render the content. This has the big advantage of automatically using the Model-View-Controller concept with the configured stock symbols as model, the JSP as view, and the portlet code as controller.

    After the model and the controller (which are in the portlet code) are implemented, we can dynamically change the view, enabling us not only to easily work on the layout but also making it easy to debug, as the JSP can access the Portlet API as well. So we can put debugging statements into the JSP without having to redeploy or update the portlet itself.

    In our example portlet we configure the name of the JSP within the web.xml (see Listing 4). These names are accessible via the PortletConfig:

    ...
    String jspName = getPortletConfig().getInitParameter(VIEW_JSP);
    ...

    The PortletConfig file provides the Portlet class with its initial configuration. This information is valid for every concrete portlet derived from the portlet.

    A portlet's configuration is set by the portlet developer and initially read from its associated servlet from the Web deployment descriptor. The configuration is read-only and cannot be changed by the portlet. The PortletConfig is passed to the portlet in the init() method of the abstract Portlet class and is used to access portlet-specific configuration parameters using getInitParameters().

    After getting the name, the JSP is included by using the PortletContext:

    ...
    getPortletConfig().getContext().include("/WEB-INF/jsp/"
    +jspName, request, response);
    ...

    The PortletContext interface defines a portlet's view of the portlet container within which each portlet is running. The PortletContext also allows a portlet to access resources available to it. Using the context, a portlet can access the portlet log, access context parameters common to all portlets within the portlet application, obtain URL references to resources, or access portlet services.

    Now that we're able to set configuration parameters, access them in the source code, and call/include resources, let's start implementing the portlet.

    First we list the stock symbols in the view JSP previously configured in the EDIT mode and stored persistently in PortletData.

    The PortletData is a simple means for the portlet to store data persistently on the instance level, allowing each portlet instance to store and read its own data. The portlet may get, set, and remove attributes during one request. To commit the changes, the store() method has to be called, otherwise all data is lost after the request. The data is read-only and can be written by the portlet only when it is in EDIT mode.

    In our example we just want to read them in the VIEW: get all the symbols and loop through the parameters, displaying their name (attribute name), their description (attribute value) if required, and a random number as stock value (see Listing 5).

    In addition, we want a link to switch to symbol details. Such a link is to be implemented on the base of a PortletURI object.

    The PortletURI object contains a URI pointing to the portlet instance and can be further extended by adding portlet-specific parameters and by attaching actions (see EDIT mode below). The complete URI can be converted to a string that's ready for embedding into markup. The PortletResponse provides us with all necessary methods to create such a URI.

    The PortletResponse encapsulates information to be returned from the server to the client by using a Java PrintWriter and is passed via the beginPage(), endPage(), and service() method. The response also includes methods for creating the PortletURI object (as mentioned above) or qualifying portlet markup with the portlet's namespace.

    Each portlet runs in its own unique namespace. The method encodeNamespace() is used by portlets to bring attributes into the portlet's output to avoid name clashes with other portlets on the same page. Attributes can include parameter names, global variables, or JavaScript function names.

    After creating the URI we can add parameters or actions to it and convert it to a string that can be used within our html link.

    As the link is put together in the JSP, the URI is given to the JSP in a bean that also contains the message for the link plus a Boolean value to indicate whether the description will be shown (see Listing 6). We used that value above when listing the stock symbols. This bean is added to the request, from which the JSP can get it again via the JSP useBean tag.

    In the EDIT mode we want to enable users to personalize their portlet with some stock symbols. These symbols are stored in the PortletData as shown below:

    ...
    PortletData data = event.getRequest().getData();

    data.setAttribute(name, desc);

    ...

    data.store();
    ...

    The data to be stored is collected via the StocksEdit.jsp's form. Submitting the form triggers a PortletAction.

    Actions are portlet-specific activities that need to be performed as result of the incoming request, but before the service() method of the portlet is called. For example, when a user is entering the data in the portlet's edit mode and clicks the "Save" button, the portlet needs to process the posted data before the next markup is generated. This is the case, as the action brings the new stock symbol to the portlet, which then wants to display the new symbol right away. This can be achieved by adding a "Save" action to the URI that represents the "Save" button (see Listing 7).

    For the portlet to receive the action it must implement the ActionListener interface as shown:

    ...
    // ActionListener interface method
    public void actionPerformed (ActionEvent event)
    throws PortletException
    {

    DefaultPortletAction action =
    (DefaultPortletAction) event.getAction();
    ...
    }

    The content of the form can be retrieved as a parameter of the PortletRequest to be stored as shown:

    if (action.getName().equalsIgnoreCase(STOCKS_ADD))
    {
    String name = (String) event.getRequest().getParameter(STOCKS_NAME);
    String desc = (String) event.getRequest().getParameter(STOCKS_DESC);
    ...
    }

    The PortletRequest object is providing the portlet with request-specific data and the opportunity to access information such as:

  • Attributes: Attributes are name/value pairs associated with a request. Attributes are available only for the scope of the request. The portlet can get, set, and remove attributes during one request.

  • Parameters: Parameters are name/value pairs sent by the client in the URI query string as part of a request. Often the parameters are posted from a form. Parameters are available for the scope of a specific request. The portlet can get - but not set - parameters from a request.

    Now we have the code for entering new stock symbols and we have seen how to display them in the VIEW mode; that leaves us with the function to delete the symbols. This is just another action that's put into a link within the edit JSP:

    ...
    <A HREF='<portletAPI:createURI><portletAPI:URIAction
    name='<%=StocksPortlet.STOCKS_DELETE%>'/>
    </portletAPI:createURI>'>delete all</a>
    ...

    With help of the actions' names we can identify what to do in the ActionListener (see Listing 8)

    Conclusion
    This article only scratches the surface of the potential in portlet programming. We've shown how to get started in portlet programming, including setting up a portlet development and runtime environment. We used the HelloWorld portlet to demonstrate a very basic portlet and give you a feel for the basic structure of a portlet, as well as how to build, package, and deploy a portlet on a portal server. We also introduced the concepts of portlet modes and portlet window states, the use of JSP components and JavaBeans to render data in a portlet, and portlet action handling with the help of the stocks portlet.

    These concepts make up the basics of portlet programming. If you combine these concepts with your existing application's data connectors, you will be able to build powerful portlets and bring your product into the portal era of the Internet.

    To get some more practice in developing portlets, we suggest extending the example portlet step by step with additional functions. As a starting point you could implement the deletion of single stock quotes.

    Resources

  • WebSphere Portal Server: www-4.ibm.com/software/webservers.
  • WebSphere InfoCenter: www-4.ibm.com/software/webservers/portal/library/InfoCenter.
  • IBM Portlet Development Guide: www-4.ibm.com/software/webservers/portal/library.
  • More Stories By Peter Fischer

    Peter Fischer is an IT Specialist and software developer for IBM WebSphere Portal. You can contact Peter at peter.fischer@de.ibm.com.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
    "MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...