JSP Best Practices

As discussed in CSS Best Practices and JavaScript Best Practices portlets require that all HTML element ids be namespaced to prevent duplicate ids on a page when a portlet is included multiple times on a page.  Some JSP tag libraries automatically generate ids if they are not specified, so a developer should specify the ids.  For example

<!-- Spring form tag will cause duplicate ids -->
<form:select path="title" items="${titles}" />

<!-- when rendered might look something like this -->
<select id="title" name="title">
  <option value="Mr">Mr</option>
  <option value="Mrs">Mrs</option>
  <option value="Miss">Miss</option>
</select>

<!-- Instead specify a namespaced id -->

<c:set var="n"><portlet:namespace /></c:set>

<form:select id="${n}title" path="title" items="${titles}" />

defineObjects tag

The defineObjects tag creates a number of useful variables that the JSP page can use.  Refer to the JSR-286 Spec for more information.  Make sure you have the v2.0 of the portlet URI when defining the portlet prefix.

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


<!-- Page can now access user preferences values. -->
 
<p>Hello ${portletPreferencesValues['prefName'][0]}</p>
 
<!-- Access to portlet session attributes as a map -->
 
<p>You last said ${portletSessionScope['conversation'].lastItem}</p>
 
<!-- Access to portlet config -->
 
<p>Portlet's static name from portlet.xml is ${portletConfig.portletName}</p>

Miscellaneous

  • You can access environment variables using markup such as <p>USER environment variable=<spring:eval expression="@systemEnvironment['USER']"/></p> (TBD Verify this)

Â