August 2006: JSR-168: The Portlet Specification

JSR-168: The Portlet Specification

By Enrique Lara, OCI Software Engineer and Consultant

August 2006


Overview

JSR 168: Portlet Specification was constructed "to enable interoperability between Portlets and Portals." This article will focus on the Portlet side of things, by showing how to create a simple Portlet and deploying that into a Portal. We will then refactor and extend the Portlet to see how some of the patterns of Servlet development might be used. Along the way we will exercise different aspects of the API available to a JSR—168 Portlet developer. It is assumed that the reader is familiar with Java, Web applications, and Maven.

Hello World Portlet

We will be building a Portlet which will display random quotes by random authors. Maven 2.x will be used to construct a .war file to be deployed into the Jetspeed-2 JSR—168 compliant Portal.

Java Source

This Portlet generates an HTML fragment manually and uses the GenericPortlet convenience class as a parent. The GenericPortlet "...dispatches requests to the doViewdoEdit or doHelp method depending on the portlet mode." Our example below will only support the VIEW mode at this point. Note that the CSS class definitions would be provided by the Portal.

  1. // src/main/java/com/ociweb/portletapi/Quote1HelloWorldPortlet.java
  2. package com.ociweb.portletapi;
  3.  
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6.  
  7. import javax.portlet.GenericPortlet;
  8. import javax.portlet.PortletException;
  9. import javax.portlet.RenderRequest;
  10. import javax.portlet.RenderResponse;
  11.  
  12. import org.apache.commons.logging.Log;
  13. import org.apache.commons.logging.LogFactory;
  14.  
  15.  
  16. public class Quote1HelloWorldPortlet extends GenericPortlet {
  17. private static final Log log = LogFactory.getLog(Quote1HelloWorldPortlet.class);
  18.  
  19. public void doView(RenderRequest request, RenderResponse response)
  20. throws PortletException, IOException {
  21. log.debug("doView");
  22. response.setContentType("text/html");
  23. PrintWriter out = response.getWriter();
  24. out.print("<div class=\"portlet-section-header\">Quote</div>");
  25. out.print("<div class=\"portlet-section-body\">");
  26. out.print("Awesome Quote<br />");
  27. out.print("by Author");
  28. out.print("</div>");
  29. }
  30. }

Web Application Configuration

A Portlet application is also a Web application — so we must define the web.xml deployment descriptor.

  1. <!-- src/main/webapp/WEB-INF/web.xml -->
  2. <?xml version="1.0" encoding="ISO-8859-1"?>
  3. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  4. "http://java.sun.com/dtd/web-app_2_3.dtd">
  5. <web-app>
  6. <display-name>QuotePortlets</display-name>
  7. <description>Quote Portlets</description>
  8. </web-app>

Portlet Configuration

In addition to a web.xml, we must define a Portlet application deployment descriptor. As described in the specification, "the portlet.xml contains configuration information for the portlets."

  1. <!-- src/main/site/examples/portlet.xml -->
  2. <?xml version="1.0" encoding="ISO-8859-1"?>
  3. <portlet-app>
  4. <portlet>
  5. <portlet-name>Quote1HelloWorldPortlet</portlet-name>
  6. <portlet-class>com.ociweb.portletapi.Quote1HelloWorldPortlet</portlet-class>
  7. <expiration-cache>3600</expiration-cache>
  8. <supports>
  9. <mime-type>text/html</mime-type>
  10. <portlet-mode>VIEW</portlet-mode>
  11. </supports>
  12. <portlet-info><title>Quote1HelloWorldPortlet</title></portlet-info>
  13. </portlet>
  14. </portlet-app>

Building the WAR

We'll let Maven do a lot of the work of setting up the java classpath and packaging things. The Maven-2 project object model file is available in the example project.
With Maven rocking and rolling, we can create our project artifact — a .war file — by typing the following command:

% mvn package

Deployment into Jetspeed2

Make sure that Jetspeed-2 is installed. The environment variable CATALINA_HOME is assumed to to match the Jetspeed-2 installation directory. First, deploy the portlet:

% cp target/quote-portlets.war $CATALINA_HOME/webapps/jetspeed/WEB-INF/deploy

Then start the portal, by starting the Servlet Container.

% $CATALINA_HOME/bin/startup

Now, we create a new "page" which indicates to Jetspeed-2 that it should render our Portlet. Jetspeed-2 will also display other Portal goodies (navigation, login box, logos) on this screen:

  1. <!-- src/main/site/examples/quote.psml -->
  2. <page id="quotes">
  3. <defaults
  4. skin="orange"
  5. layout-decorator="tigris"
  6. portlet-decorator="gray-gradient"
  7. ></defaults>
  8. <title>Quote Portlet</title>
  9. <metadata name="title" xml:lang="es">Citas</metadata>
  10. <metadata name="short-title" xml:lang="es">Quotes</metadata>
  11. <fragment id="quotes-1" type="layout" name="jetspeed-layouts::VelocityTwoColumns">
  12. <fragment id="quotes-101" type="portlet" name="quote-portlets::Quote1HelloWorldPortlet">
  13. <property layout="TwoColumns" name="row" value="0" ></property>
  14. <property layout="TwoColumns" name="column" value="0" ></property>
  15. </fragment>
  16. </fragment>
  17. <security-constraints>
  18. <security-constraints-ref>public-edit</security-constraints-ref>
  19. </security-constraints>
  20. </page>

The Quote Portlet should now be viewable by navigating to the Quote Page.

Refactor our Basic Portlet

Now we will bring over some programming conventions that have made Web application development and maintenance go a lot more smoothly.

Introduce Model Tier

The first example didn't quite meet the "random" aspect of our requirements, so let's create a Quote domain object and a QuoteService (implementations available in the example project).

  1. // src/main/java/com/ociweb/portletapi/Quote.java
  2. package com.ociweb.portletapi;
  3.  
  4. public interface Quote {
  5. public String getQuote();
  6. public String getAuthor();
  7. }
  1. // src/main/java/com/ociweb/portletapi/QuoteService.java
  2. package com.ociweb.portletapi;
  3.  
  4. import java.util.List;
  5.  
  6. public interface QuoteService {
  7. public List getRandomQuotes(int count);
  8. }
  1. // src/main/java/com/ociweb/portletapi/Quote2QuoteAPIPortlet.java
  2. ...
  3. public void doView(RenderRequest request, RenderResponse response)
  4. throws PortletException, IOException {
  5. log.debug("doView");
  6. response.setContentType("text/html");
  7. PrintWriter out = response.getWriter();
  8.  
  9. QuoteService quoteService = (QuoteService) ComponentManager.getObject(QuoteService.class);
  10. List quotes = quoteService.getRandomQuotes(1);
  11. Quote quote = (Quote)quotes.get(0);
  12.  
  13. out.print("<div class=\"portlet-section-header\">Quote</div>");
  14. out.print("<div class=\"portlet-section-body\">");
  15. out.print(quote.getQuote() + "<br />");
  16. out.print("by " + quote.getAuthor());
  17. out.print("</div>");
  18. }
  19. ...

Separate Presentation Logic

Now that we have an object model, maybe we can separate our data acquisition from how we want to display that to the user. In this example, let's use Java Server Pages technology (JSP) to manage the presentation details of the data.
We'll modify the Java code to delegate HTML fragment generation to a JSP.

  1. // src/main/java/com/ociweb/portletapi/Quote3RenderJSPPortlet.java
  2. ...
  3. QuoteService quoteService = (QuoteService) ComponentManager.getObject(QuoteService.class);
  4. List quotes = quoteService.getRandomQuotes(1);
  5. Quote quote = (Quote)quotes.get(0);
  6.  
  7. request.setAttribute("quote", quote);
  8.  
  9. String jspFilePath = "/WEB-INF/templates/jsp/html/view/quote3-render-jsp.jsp";
  10. PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(jspFilePath);
  11. rd.include(request,response);
  12. ...

The jsp uses the portlet tag library which "enables JSPs ... to have direct access to portlet specific elements." The renderRequest used below is one such element.

  1. <!-- src/main/webapp/WEB-INF/templates/jsp/html/view/quote3-render-jsp.jsp -->
  2. <%@ page session="false" contentType="text/html" import="java.util.*,javax.portlet.*,com.ociweb.portletapi.*" %>
  3. <%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
  4. <portlet:defineObjects></portlet:defineObjects>
  5. <%
  6. Quote quote = (Quote)renderRequest.getAttribute("quote");
  7. %>
  8. <div class="portlet-section-header">Quote</div>
  9. <div class="portlet-section-body">
  10. <%= quote.getQuote() %><br />
  11. by <%= quote.getAuthor() %>
  12. </div>

Re-Build and Re-Deploy

Jetspeed-2 will re-load the portlet appliction, so the steps for pushing these changes can be as simple as repackaging the .war file and copying this into the deployment directory. Tomcat may be up and running for this, but Jetspeed-2 seems to prefer that Tomcat is restarted after a redeployment.

% mvn package
% cp target/quote-portlets.war $CATALINA_HOME/webapps/jetspeed/WEB-INF/deploy
% $CATALINA_HOME/bin/shutdown
% $CATALINA_HOME/bin/startup

Respond to Portlet Preferences

In the next few steps we will enhance our example to take advantage of the personalization features defined in the Portlet Specification. Specifically, we will access the portlet preferences as well as allow an end user to edit these values. Additionally, we will also introduce the EDIT mode and the processAction method.

Configuring Preferences

Instead of hard-coding the number of Quotes to display, we declare that in the Portlet deployment descriptor.

  1. <!-- src/main/site/examples/preferences-portlet.xml -->
  2. <portlet>
  3. ...
  4. <portlet-preferences>
  5. <preference>
  6. <name>nQuotes</name>
  7. <value>6</value>
  8. </preference>
  9. </portlet-preferences>
  10. ...
  11. </portlet>

Accessing Preferences

The Java code can access this preference information by querying the PortletRequest.

  1. // src/main/java/com/ociweb/portletapi/Quote4PreferencesPortlet.java
  2. ...
  3. final QuoteService quoteService = (QuoteService) ComponentManager.getObject(QuoteService.class);
  4.  
  5. public final static String PREF_NUM_QUOTES = "nQuotes";
  6. final static int DEFAULT_NUM_QUOTES = 5;
  7.  
  8. private Integer getNumQuotes(PortletRequest request) {
  9. Integer nQuotes = new Integer(DEFAULT_NUM_QUOTES);
  10. try {
  11. PortletPreferences prefs = request.getPreferences();
  12. String strNQuotes = prefs.getValue(PREF_NUM_QUOTES, nQuotes.toString());
  13. nQuotes = Integer.valueOf(strNQuotes);
  14. } catch(Exception e) {
  15. log.warn("Problems obtaining preference:" + PREF_NUM_QUOTES, e);
  16. }
  17. return nQuotes;
  18. }
  19.  
  20.  
  21. public void doView(RenderRequest request, RenderResponse response)
  22. throws PortletException, IOException {
  23. log.debug("doView");
  24.  
  25. int nQuotes = getNumQuotes(request).intValue();
  26. List quotes = quoteService.getRandomQuotes(nQuotes);
  27. request.setAttribute("quotes", quotes);
  28. renderJSP(request, response, "/WEB-INF/templates/jsp/html/view/quote4-preferences.jsp");
  29. }
  30. ...

We must also modify our JSP to support this change.

  1. <!-- src/main/webapp/WEB-INF/templates/jsp/html/view/quote4-preferences.jsp -->
  2. <%@ page session="false" contentType="text/html" import="java.util.*,javax.portlet.*,com.ociweb.portletapi.*" %>
  3. <%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
  4. <portlet:defineObjects></portlet:defineObjects>
  5. <%
  6. List quotes = (List)renderRequest.getAttribute("quotes");
  7. String header = (quotes.size() > 1) ? "Quotes" : "Quote";
  8. %>
  9. <div class="portlet-section-header"><%= header %></div>
  10. <div class="portlet-section-body">
  11. <ul>
  12. <%
  13. Iterator it = quotes.iterator();
  14. while(it.hasNext()) {
  15. Quote quote = (Quote) it.next();
  16. %>
  17. <li><%= quote.getQuote() %><br />
  18. by <%= quote.getAuthor() %></li>
  19. <% } %>
  20. </ul></div>

Editing Preferences

We want to let users change the number of quotes being displayed. This implies a change of state in the Portlet. The specification denotes that "commonly, during a render request, portlets generate content based on their current state." The doView and doEdit methods we have been using thus far originate in the render method of the GenericPortlet parent class. The specification describes an action request which is more geared towards state changes. The processAction method is the part of the Portlet API called to handle such requests, and would probably be a good spot to handle the Portlet preference modifications.

  1. // src/main/java/com/ociweb/portletapi/Quote4PreferencesPortlet.java
  2. <pre xml:space="preserve">...
  3. public void processAction(ActionRequest request, ActionResponse response)
  4. throws PortletException, IOException {
  5. log.debug("processAction");
  6. String nQuotes = request.getParameter("nQuotes");
  7. PortletPreferences prefs = request.getPreferences();
  8. prefs.setValue(PREF_NUM_QUOTES, nQuotes);
  9. prefs.store();
  10. }
  11. ...
  12. </pre>

Since we will be editing the portlet, we would probably be better off exposing this functionality in the EDIT Portlet mode.

  1. // src/main/java/com/ociweb/portletapi/Quote4PreferencesPortlet.java
  2. ...
  3. public void doEdit(RenderRequest request, RenderResponse response)
  4. throws PortletException, IOException {
  5. log.debug("doEdit");
  6.  
  7. Integer nQuotes = getNumQuotes(request);
  8. request.setAttribute("nQuotes", nQuotes);
  9. renderJSP(request, response, "/WEB-INF/templates/jsp/html/edit/quote4-preferences.jsp");
  10. }
  11. ...

Let's also add a new JSP to present an HTML form to the user. The form action value is generated using the portlet tag-lib. This Action URL will flag Jetspeed-2 to call the processAction method on this Portlet before proceeding with the rendering of the page's defined Portlets.

  1. <!-- src/main/webapp/WEB-INF/templates/jsp/html/edit/quote4-preferences.jsp -->
  2. <%@ page session="false" contentType="text/html" import="java.util.*,javax.portlet.*,com.ociweb.portletapi.*" %>
  3. <%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
  4. <portlet:defineObjects></portlet:defineObjects>
  5. <%
  6. Integer nQuotes = (Integer)request.getAttribute("nQuotes");
  7.  
  8. %>
  9. <div class="portlet-section-header">Edit</div>
  10. <div class="portlet-section-body">
  11. <form action="<portlet:actionURL ></form>" method="POST">
  12. Number Quotes: <input type="text" name="nQuotes" value="<%= nQuotes %>" >
  13. <input type="submit" name="Submit" value="Set Preference" >
  14. </form>
  15.  
  16. </div>

In order to give the user access to this new Portlet screen, we must make sure to update Portlet deploment descriptor so that the Portal knows that EDIT is supported. Jetpseed-2 exposes this by adding an Edit link to the Portlet title bar.

  1. <!-- src/main/site/examples/preferences-view-mode-portlet.xml -->
  2. <portlet>
  3. ...
  4. <supports>
  5. <mime-type>text/html</mime-type>
  6. <portlet-mode>VIEW</portlet-mode>
  7. <portlet-mode>EDIT</portlet-mode>
  8. </supports>
  9. ...
  10. </portlet>

Validate Preference Value

When it comes to storing Portlet Preferences, the Portlet Specification defines the PreferencesValidator interface. A class implementing this interface may be associated to the Portlet to verify the validity of the preference values.

  1. // src/main/java/com/ociweb/portletapi/Quote4PreferencesValidator.java
  2. package com.ociweb.portletapi;
  3.  
  4. import java.util.ArrayList;
  5. import java.util.Collection;
  6.  
  7. import javax.portlet.PortletPreferences;
  8. import javax.portlet.PreferencesValidator;
  9. import javax.portlet.ValidatorException;
  10.  
  11. import org.apache.commons.logging.Log;
  12. import org.apache.commons.logging.LogFactory;
  13.  
  14. public class Quote4PreferencesValidator implements PreferencesValidator {
  15. private static final Log log = LogFactory.getLog(Quote4PreferencesValidator.class);
  16.  
  17. public void validate(PortletPreferences preferences) throws ValidatorException {
  18. log.debug("validate");
  19.  
  20. Collection keys = new ArrayList();
  21. keys.add(Quote4PreferencesPortlet.PREF_NUM_QUOTES);
  22.  
  23. String value = preferences.getValue(Quote4PreferencesPortlet.PREF_NUM_QUOTES, null);
  24.  
  25. if(value == null) {
  26. throw new ValidatorException(" Values must not be null.", keys);
  27. }
  28. if(value.length() < 1) {
  29. throw new ValidatorException(" Values must not be blank.", keys);
  30. }
  31. try {
  32. int iValue = Integer.parseInt(value);
  33. if(iValue < 1) {
  34. throw new ValidatorException(" Values must not be less than 1.", keys);
  35. }
  36. } catch(NumberFormatException e) {
  37. throw new ValidatorException(e, keys);
  38. }
  39.  
  40. log.debug("validate success.");
  41. }
  42.  
  43. }

The Portal will use the above implementation to assert that the preferences are valid.
The Portlet deployment descriptor must first declare this association.

  1. <!-- src/main/site/examples/preferences-val-portlet.xml -->
  2. <portlet>
  3. ...
  4. <portlet-preferences>
  5. <preference>
  6. <name>nQuotes</name>
  7. <value>6</value>
  8. </preference>
  9. <preferences-validator>com.ociweb.portletapi.Quote4PreferencesValidator</preferences-validator>
  10. </portlet-preferences>
  11. ...
  12. </portlet>

Summary

JSR—168 paves the way for a personalized user experience with content from a wide range of sources all centralized in one easy-to-find location. The API gives developers a roadmap for producing plug-and-play applications that can instantly add value to a Web site. There are some frameworks available to provide some of the structure available to Servlet programmers (JSF, WSRP, Struts-Bridges, Spring); however, these do seem to be in their infancy and there is a lot of room for new conventions and libraries to simplify the common cases.

References

Enrique Lara would like to thank Tom Wheeler and Jeremy Ford for reviewing this article.

 

The Software Engineering Tech Trends is a monthly newsletter featuring emerging trends in software engineering.

Subscribe

© Copyright Object Computing, Inc. 1993, 2016. All rights reserved

secret