JSPs (Java Server Pages) provide a powerful way to build web pages dynamically. They are the way, web pages are generated in OpenCms. In essence a JSP is a Java program that looks like HTML code and, if executed, creates a HTML page. The particular advantage of a JSP is that arbitrary Java code can be executed to produce HTML output. There are three ways to accomplish dynamic HTML creation by executing Java code:

  • Special tags provided via taglibs
  • The expression language (EL)
  • Writing scriptlet code

In order to keep your JSPs simple and maintainable, it is good style to avoid scriptlet code and use tags and the EL. For more details about JSPs in general, in particular the JSTL (the standard tag libraries) and the EL, please consult the very good books or tutorials around.

When writing JSPs in OpenCms, you should be aware of the following:

  • JSP are managed / added via the OpenCms workplace and have the resource type “jsp”
  • Each JSP exists in an “offline” and an “online” version
  • JSPs can be exported statically
  • To increase performance you might have to alter FlexCache settings

In OpenCms JSPs are used for several purposes:

  • Templates that provide for WYSIWYG editable pages
  • Formatters for XML contents
  • Pages with special functionality, e.g. login forms, search result pages, etc.

To easily create JSPs for the just described purposes, OpenCms comes with a special API for JSPs that consists mainly of two parts:

The JSP <cms>-taglib

1.1 How to insert the "taglib" directive?

If you like to use the OpenCms JSP taglib, you must insert the "taglib" directive in your JSP page to specify where the OpenCms taglib definition can be found. This can be done in two different ways:

  1. With the standard JSP-/Servlet-technology:
<%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %>

This directive must be set before any cms tags are used. If used like shown in the example, the prefix cms is unique for the OpenCms Taglib. In our examples, all tags of the OpenCms taglib start with the prefix cms:.

  1. With OpenCms specific short form:
<%@page buffer="none" session="false" taglibs="c,cms" %>

1.2 Tags exposed by the OpenCms taglib

The following list of <cms>-tags is available in the OpenCms standard taglib. A tag can be executed by calling:

<cms:tagName attributes...></cms:tagName>
Tags exposed by the OpenCms taglib
cms:bundle

Loads a resource bundle to be used by its tag body. The tag is similar to <fmt:bundle>, but able to handle OpenCms' XML-bundles.

cms:container

Enables the template mechanism for container pages.

cms:contentaccess

Provides access to the content for the JSP EL.

cms:contentcheck

Provides conditional logic for checking the element of a XML content.

cms:contentinfo

Provides access to the result set of a contentload.

cms:contentload

Loads XML content items from the OpenCms VFS.

cms:contentloop

Allows looping through XML content node element values.

cms:contentshow

Provides access to individual XML content node element values.

cms:decorate

Provides decoration of HTML content.

cms:device

Provides different HTML output for various device types.

cms:editable

Enables the direct editing within a template.

cms:elementsetting

Provides access to the settings of an ADE container element.

cms:enable-ade

Enables the advanced direct editing within a template.

cms:export

Writes JSP code from a JSP to files in the static export.

cms:formatter

Loads single XML content items for ADE formatters.

cms:headincludes

Includes required CSS or Javascript resources, placed in html/head.

cms:img

Supports image scaling using the OpenCms native image scaling mechanism.

cms:include

Includes other JSP elements dynamically at runtime.

cms:info

Enables access to some system information like OpenCms version etc.

cms:jquery

Allows to include jQuery, some jQuery plugins code and stylesheets.

cms:label

Reads localized values from resource bundles (Java property files like workplace.properties) that hold user messages.

cms:link

Builds a valid OpenCms URL for a given resource.

cms:navigation

Provides access to the navigation information.

cms:nocache

Sends no-cache headers to the browser.

cms:param

Adds a parameter to the outer tag (if supported).

cms:parse

Decorates HTML with custom A_CmsConfiguredHtmlParser implementations given in the parserClass attribute.

cms:pdf

This tag is used to generate a link to a PDF generated from an XML content given the path of the XML content.

cms:pdfthumbnail

This tag is used to generate a link to a thumbnail for a PDF.

cms:property

Enables read access to the current VFS file's properties.

cms:resourceaccess

Provides access to the resources for the JSP EL.

cms:resourceload

Loads resources from the OpenCms VFS.

cms:secureparams

Enables automatic parameter escaping for the current flex request.

cms:template

Splits a JSP page into elements to be included by the <cms:include>-tag.

cms:user

Enables access to the properties of the currently logged in user.

cms:usertracking

Performs user tracking actions like visit resources or subscribe/unsubscribe.

1.3 EL functions exposed by the OpenCms taglib

The following list of EL-functions are available in the OpenCms standard taglib. An EL-function can be accessed by calling:

${cms:functionName(parameters)}
EL functions exposed by the OpenCms taglib
cms:convertDate

Allows conversion of Long values to Dates. Can also handle Strings that represent a Long or a Date.

cms:convertList

Returns a list of attribute values specified by the attribute name of the items of the given list.

cms:convertLocale

Allows conversion of Objects to Locales. Can also handle Strings that are locales, or Locales itself.

cms:convertUUID

Allows conversion of String values to CmsUUIDs. Can also handle byte[] that are CmsUUIDs, or CmsUUID itself.

cms:escape

Encodes a String in a way that is compatible with the JavaScript escape function.

cms:getCmsObject

Returns the current OpenCms user context from the page context.

cms:getListSize

Returns the size of the given list.

cms:getRequestLink

Returns the link without parameters from a String that is formatted for a GET request.

cms:getRequestParam

Returns the value of a parameter from a String that is formatted for a GET request.

cms:lookup

Uses the 1st String as key to look up from the map that is passed as the 2nd String, and returns either the element found or the empty String. The map String must have the form key1:value1|key2:value2 etc.

cms:lookupDefault

Uses the 1st String as key to look up from the map that is passed as the 2nd String, and returns either the element found or the default value from the 3rd String. The map String must have the form key1:value1|key2:value2 etc.

cms:navUri

Returns the current navigation URI.

cms:stripHtml

Strips all HTML markup from the given input.

cms:trimToSize

Returns a substring of the input, which isn’t longer than the given int value.

cms:unescape

Decodes a String in a way that is compatible with the JavaScript unescape function.

cms:vfs

Provides simple access to a OpenCms JSP / EL content VFS access bean.

Accessing OpenCms functionality via the EL

OpenCms comes with several Java beans to provide access to OpenCms-specific functionality in JSPs. In general, if required, an object of each bean could be made available separately in a JSP. Also several tags of the <cms:>-taglib initialize and expose objects of such beans (see here).

Since OpenCms 9.0.1 the variable cms is present in the page scope for each JSP. It makes an object of type org.opencms.jsp.util.CmsJspStandardContextBean available. The object provides a convenient way to access the most important OpenCms functions via JSTL/EL. Thus, in most cases no bean at all has to be included and initialized manually, and also formerly required use of scriptlet code becomes obsolete.

The standard context bean has a very rich interface. In particular, access to several other Java beans shipped with OpenCms is granted. A complete overview of the functionality exposed via the standard context bean can be looked up in the JavaDoc. Look up the documentation of the class CmsJspStandardContextBean. Starting there, you can easily explore the interfaces of all other beans accessible via the standard context bean as well. Aware of the naming conventions for Java Beans, you obtain an overview of the properties available in EL.

Here, we describe only the most important Java beans shipped with OpenCms. We do not aim for completeness when describing the properties of the beans. We do also not cover all beans.

2.1 The standard context bean

2.1.1 Provider and availability

Provider class

org.opencms.jsp.util.CmsJspStandardContextBean

Access via

cms

Availability

In each JSP, initialized according to the current request.

2.1.2 Useful properties in a template

List of properties useful in a template
Title

Get the title property of the currently requested page. Note, that the property has a special behavior for detail pages: Instead of using the title property of the displayed page, the title property of the resource providing the detail content is chosen.

isOnlineProject

Returns true if the request is performed in the “online” project. Otherwise returns false.

isEditMode

Returns true if edit mode is enabled. Otherwise returns false.

We exemplify the use of the properties in a template. The tasks are as follows:

  • Insert minimized javascript sources only in the online project, for debug reasons use the standard version otherwise
  • Set the page title of the web page according to the requested resource.
  • Place a special placeholder on top of the page if (and only if) in edit mode

The following code snippet fulfills the three tasks:

<html>
 <head>
  <title>${cms.title}</title>	
  <!-- meta info etc. -->
  <cms:enable-ade/>
  <c:choice>
   <c:when test="${cms.isOnlineProject}">
    <cms:headincludes type="javascript" 
                      defaults="%(link.weak:/.../jquery-1.10.2.min.js)" />
   </c:when>
   <c:otherwise>
    <cms:headincludes type="javascript" 
                      defaults="%(link.weak:/.../jquery-1.10.2.js)" />
   </c:otherwise>
  </c:choice>
 </head>
 <body>
  <c:if test="${cms.isEditMode}">
   <!--=== Placeholder for OpenCms toolbar in the offline project ===-->
   <div style="background: lightgray; height: 35px">&nbsp;</div>
  </c:if>
  <!-- Further code for creating the template -->
 </body>
</html>

2.1.3 Useful properties for localization

OpenCms supports a multi-language design for web pages. Thus, functionality and especially text output might be language specific. Which language to choose should be selected via a locale parameter. The standard context bean provides two choices for such locales:

List of useful properties for localization
locale

Returns the locale that is specific for the request context. The same locale is returned by cms.requestContext.locale.

workplaceLocale

Returns the locale configured in the workplace of the current user.

Here is a toy example:

<p>The locale of the request specific locale is "${cms.locale}".</p>

<p>The locale of your workplace is "${cms.workplaceLocale}".</p>

<p>To change the request specific locale, add the parameter "__locale=de" to the url.</p>

<p>The workplace locale is set via the preferences in your OpenCms workplace.</p>

2.1.4 Useful properties for formatting elements

It is sometimes useful to adjust formatters or function providers depending on the context. The standard context bean provides the following useful properties:

List of useful properties for formatting elements
edited

Returns true if the element was re-rendered without reloading the whole page, e.g., after editing the element’s content or moving the element on the page. This state might lead to limited functionality of javascript. Therefore, you might display just a “please reload” message.

enableReload

Placing ${cms.enableReload} somewhere in your formatter will result in an automatically page reload when a content is edited (or moved to a different container).

element

Returns the currently rendered element.
Return type: org.opencms.xml.containerpage.CmsContainerElementBean

container

Returns the container the currently rendered element is part of.
Return type: org.opencms.xml.containerpage.CmsContainerBean

detailContent

Returns the current detail content, or null if no detail content is requested.
Return type: org.opencms.file.CmsResource (see here)

detailPageAvailable

Returns true if a detail page is available for the current element.

detailRequest

Returns true if this is a request to a detail page.

2.1.5 Useful properties to access further interesting Java beans

Via the following properties, you obtain objects of the given beans, that are initialized according to the current request.

List of useful properties to access further interesting Java beans
requestContext

Access to the request context bean org.opencms.file.CmsRequestContext.

vfs

Access to the VFS access bean org.opencms.jsp.util.CmsJspVfsAccessBean.

Note that here more properties that return objects of further Java beans are explained. In contrast to the properties listed above, these properties make only sense when formatting elements in container pages.

2.2 The request context bean

In OpenCms there is much more request specific information than in a usual stand-alone JSP. The request context bean provide access to such information. Do not confuse an object of such a bean with the implicitly present object requestScope that does not provide OpenCms specific information.

2.2.1 Provider and availability

Provider class

org.opencms.file.CmsRequestContext

Access via

cms.requestContext

Availabiliity

In each JSP, initialized according to the current request.

2.2.2 Useful properties of general interest

List of properties of general interest
uri

Returns the OpenCms VFS URI of the requested resource.

2.2.3 Useful properties in a template

List of properties useful in a template
encoding

Returns the current content encoding to be used in HTTP response.

The encoding property should be used to define the charset as follows:

<meta charset="${cms.requestContext.encoding}">

2.2.4 Useful properties to access further interesting Java beans

List of properties to access further interesting Java beans
currentUser

Access to the user bean org.opencms.file.CmsUser.

currentProject

Access to the project bean org.opencms.file.CmsProject.

2.3 The VFS access bean

The VFS access bean provides access to all resources in OpenCms’ virtual file system. The bean is used to check if files exist, to read and set properties and permissions, to read XML documents, etc. In principal, you can access every resource in the VFS, read its metadata or access content. To enable such functionality, most properties of the bean return a lazy map that requires the URI of a resource as key to extract a value. If the current user has no access to the resource, or the resource does not exist, the return value will be empty.

When object.property returns a map, use object.property[key] to ask for the value at key key.

2.3.1 Provider and availability

Provider class

org.opencms.jsp.util.CmsJspVfsAccessBean

Access via

cms.vfs

Availability

In each JSP, initialized according to the current request.

2.3.2 Useful properties to explore resources in the VFS

List of useful properties to explore resources in the VFS
exists

Returns true if a resource, whose URI is given as key, exists.

existsXML

Returns true if a resource, whose URI is given as key, exists and is an XML content or XML page.

property

Given an URI as key, a lazy map with property names as keys and their values as values is returned.

propertySearch

Like property, but the returned map contains also inherited values for properties.

The following example shows how to read the “NavText” property of a file and how to access a value in an XML content.

<%@page taglibs="c" %>

<c:set var="uri" value="${cms.requestContext.uri}" />

<p> The "NavText" property value of the current URI (file
    ${cms.vfs.resource[uri].name}) is 
    "${cms.vfs.property[uri]['NavText']}".
</p>
<p> The Text value of a selected Jumbotron XML content is
    "${cms.vfs.xml['/demo/.content/jumbotrons/jt_00001.xml'].value.Text}".
</p>

2.3.3 Useful properties to access further Java beans

List of useful properties to access further Java beans
permissions

Access to the permission set bean org.opencms.security.CmsPermissionSet.

resource

Access to the resource bean org.opencms.file.CmsResource.

xml

Access to the content access bean org.opencms.jsp.util.CmsJspContentAccessBean.

2.4 The user bean

The user bean provides an interface to access manifold user information.

2.4.1 Provider and availability

Provider class

org.opencms.file.CmsUser

Access via

cms.requestContext.currentUser

Availability

In each JSP, initialized according to the current request.

2.4.2 Useful properties

List of useful properties
guestUser

Returns true if the user is not logged in.

fullName

Returns “firstname lastname (username)”.

firstname

Returns the firstname of the user.

lastname

Returns the lastname of the user.

email

Returns the email of the user.

address

Returns the address of the user.

institution

Returns the institution information of the user.

In the following example JSP we check if a user is logged on. If so, we greet him with his name.

<%@page taglibs="c" %>

<c:set var="user" value="${cms.requestContext.currentUser}" />

<c:choose>
  <c:when test="${user.guestUser}">
  	You are not logged in.
  </c:when>
  <c:otherwise>Hi ${user.fullName}!</c:otherwise>
</c:choose>

2.5 The project bean

The project bean provides access to project information. In OpenCms files can belong to different projects. There is just one “online” project, but several different projects that contain “offline” resources are possible. One such project, the “offline” project is predefined.

2.5.1 Provider and availability

Provider class

org.opencms.file.CmsProject

Access via

cms.requestContext.currentProject

Availability

In each JSP, initialized according to the current request.

2.5.2 Useful properties

List of useful properties
name

Returns the name of the project.

description

Returns the description of the project.

dateCreated

Returns the creation date of the project.

uuid

Returns the id of the project.

In the following example JSP, we output when the current project’s name and creation date.

<%@page taglibs="c" %>

<c:set var="project" value="${cms.requestContext.currentProject}" />

<p> 
Your are in the project "${project.name}" that was created on
${cms:convertDate(project.dateCreated)}.
</p>

2.6 The resource bean

Each entry in the OpenCms VFS can be considered as a resource. The resource bean allows accessing metadata of such resources, such as properties, attributes, version, name, etc.

2.6.1 Provider and availability

Provider class

org.opencms.file.CmsResource

Access via

cms.vfs[<URI>].resource

Availability

Whenever the requested URI exists and the current user has the necessary permissions.

2.6.2 Useful properties

List of useful properties
dateCreated

Returns the date of the creation of this resource.

dateReleased

Returns the release date this resource.

dateExpired

Returns the expiration date this resource.

dateLastModified

Returns the date of the last modification of this resource.

dateContent

Returns the date of the last modification of the content of this resource.

name

Returns the file name of this resource without parent folders, for example “index.html”.