Scripts

JSP Scripts or Servlets are usually used to render components.

According to the request processing rules of Sling the name for the default script is <componentname>.jsp.

global.jsp

The JSP script file global.jsp is used to provide quick access to specific objects (i.e. to access content) to any JSP script file used to render a component.

Therefore global.jsp should be included in every component rendering JSP script where one or more of the objects provided in global.jsp are used.

Function of global.jsp, used APIs and Taglibs

The following lists the most important objects provided from the default global.jsp (/libs/wcm/global.jsp)

Summary:

  • <cq:defineObjects />

    • slingRequest - The wrapped Request Object (SlingHttpServletRequest).

    • slingResponse - The wrapped Response Object (SlingHttpServletResponse).

    • resource - The Sling Resource Object (slingRequest.getResource();).

    • resourceResolver - The Sling Resource Resolver Object (slingRequest.getResoucreResolver();).

    • currentNode - The resolved JCR node for the request.

    • log - The Default logger ().

    • sling - The Sling script helper.

    • properties - The properties of the addressed resource (resource.adaptTo(ValueMap.class);).

    • pageProperties - The properties of the page of the addressed resource.

    • pageManager - The page manager for accessing CQ content pages (resourceResolver.adaptTo(PageManager.class);).

    • component - The component object of the current CQ5 component..

    • designer - The designer object for retrieving design information (resourceResolver.adaptTo(Designer.class);).

    • currentDesign - The design of the addressed resource.

    • currentStyle - The style of the addressed resource.

Accessing Content

There are three methods to access content in CQ5 WCM:

  • Via the properties object introduced in global.jsp:

    The properties object is an instance of a ValueMap (see Sling API) and contains all properties of the current resource.

    Example: String pageTitle = properties.get("jcr:title", "no title"); used in the rendering script of a page component.

    Example: String paragraphTitle = properties.get("jcr:title", "no title"); used in the rendering script of a standard paragraph component.

  • Via the currentPage object introduced in global.jsp:

    The currentPage object is an instance of a page (see CQ5 API). The page class provides some methods to access content.

    Example: String pageTitle = currentPage.getTitle();

  • Via currentNode object introduced in global.jsp:

    The currentNode object is an instance of a node (see JCR API). The properties of a node can be accessed by the getProperty() method.

    Example: String pageTitle = currentNode.getProperty("jcr:title");

[Note]Note

Day does not recommend using the JCR API directly in CQ5 if not really necessary; CQ5 is a Sling Application and therefore we deal with resources and not nodes.

JSP Tag Libraries

The CQ and Sling tab libraries give you access to specific functions for use in the JSP script of your templates and components.

CQ Tag Library

The CQ tag library contains helpful CQ functions.

To use the CQ Tag Library in your script, the script must start with the following code:

<%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %>
[Note]Note

When the /libs/wcm/global.jsp file is included in the script, the cq taglib is automatically declared.

[Tip]Tip

When you develop the jsp script of a CQ5 component, it is recommended to include following code at the top of the script:

<%@include file="/libs/wcm/global.jsp"%>

It declares the sling, cq and jstl taglibs and exposes the regularly used scripting objects defined by the <cq:defineObjects /> tag. This shortens and simplifies the jsp code of your component.

<cq:setContentBundle>

The <cq:setContentBundle> tag creates an i18n localization context and stores it in the javax.servlet.jsp.jstl.fmt.localizationContext configuration variable.

It has the following attribute:

language

The language of the locale for which to retrieve the resource bundle.

The "content bundle" can be simply used by standard JSTL <fmt:message> tags. The lookup of messages by keys is two-fold:

  1. First, the JCR properties of the underlying resource that is currently rendered are searched for translations. This allows you to define a simple component dialog to edit those values.

  2. If the node does not contain a property named exactly like the key, the fallback is to load a resource bundle from the sling request (SlingHttpServletRequest.getResourceBundle(Locale)). The language or locale for this bundle is defined this way:

    1. First, if the parameter language of the<cq:setContentBundle> tag is set, this is used.

    2. Otherwise, the locale of the page is looked up. This is taken from the page path (eg. the path /content/site/en/some/page produces the "en" locale).

Example:

<%@include file="/libs/wcm/global.jsp"%><%
%><%@ page import="com.day.cq.wcm.foundation.forms.ValidationInfo,
                 com.day.cq.wcm.foundation.forms.FormsConstants,
                 com.day.cq.wcm.foundation.forms.FormsHelper,
                 org.apache.sling.api.resource.Resource,
                 org.apache.sling.api.resource.ResourceUtil,
                 org.apache.sling.api.resource.ValueMap" %><%
%><cq:setContentBundle/>
<cq:include>

The <cq:include> tag includes a resource into the current page.

It has the following attributes:

flush

A boolean defining whether to flush the output before including the target.

path

The path to the resource object to be included in the current request processing. If this path is relative it is appended to the path of the current resource whose script is including the given resource. Either path and resourceType, or script must be specified.

resourceType

The resource type of the resource to be included. If the resource type is set, the path must be the exact path to a resource object: in this case, adding parameters, selectors and extensions to the path is not supported.

If the resource to be included is specified with the path attribute that cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type.

Either path and resourceType, or script must be specified.

script

The jsp script to include. Either path and resourceType, or script must be specified.

ignoreComponentHierarchy

A boolean controlling whether the component hierarchy should be ignored for script resolution. If true, only the search paths are respected.

Example:

<%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %><%
%><div class="center">
    <cq:include path="trail" resourceType="foundation/components/breadcrumb" />
    <cq:include path="title" resourceType="foundation/components/title" />
    <cq:include script="redirect.jsp"/>
    <cq:include path="par" resourceType="foundation/components/parsys" />
</div>
[Note]Note

Should you use <%@ include file="myScript.jsp" %> or <cq:include script="myScript.jsp" %> to include a script?

  • The <%@ include file="myScript.jsp" %> directive informs the JSP compiler to include a complete file into the current file. It is as if the contents of the included file were pasted directly into the original file.

  • With the <cq:include script="myScript.jsp" %> directive, the file is included at runtime.

[Note]Note

Should you use <cq:include> or <sling:include>?

  • When developing CQ5 components, Day recommends that you use <cq:include>.

  • <cq:include> allows you to directly include script files by their name when using the script attribute. This takes component and resource type inheritance into account, and is often simpler than strict adherence to Sling's script resolution using selectors and extensions.

<cq:defineObjects>

The <cq:defineObjects> tag exposes the following, regularly used, scripting objects which can be referenced by the developer. It also exposes the objects defined by the <sling:defineObjects> tag.

componentContext

the current component context object of the request (com.day.cq.wcm.api.components.ComponentContext interface).

component

the current CQ5 component object of the current resource (com.day.cq.wcm.api.components.Component interface).

currentDesign

the current design object of the current page (com.day.cq.wcm.api.designer.Design interface).

currentPage

the current CQ WCM page object (com.day.cq.wcm.api.Page interface).

currentStyle

the current style object of the current cell (com.day.cq.wcm.api.designer.Style interface).

designer

the designer object used to access design information (com.day.cq.wcm.api.designer.Designer interface).

editContext

the edit context object of the CQ5 component (com.day.cq.wcm.api.components.EditContext interface).

pageManager

the page manager object for page level operations (com.day.cq.wcm.api.PageManager interface).

pageProperties

the page properties object of the current page (org.apache.sling.api.resource.ValueMap).

properties

the properties object of the current resource (org.apache.sling.api.resource.ValueMap).

resourceDesign

the design object of the resource page (com.day.cq.wcm.api.designer.Design interface).

resourcePage

the resource page object (com.day.cq.wcm.api.Page interface).

It has the following attributes:

requestName

inherited from sling

responseName

inherited from sling

resourceName

inherited from sling

nodeName

inherited from sling

logName

inherited from sling

resourceResolverName

inherited from sling

slingName

inherited from sling

componentContextName

specific to wcm

editContextName

specific to wcm

propertiesName

specific to wcm

pageManagerName

specific to wcm

currentPageName

specific to wcm

resourcePageName

specific to wcm

pagePropertiesName

specific to wcm

componentName

specific to wcm

designerName

specific to wcm

currentDesignName

specific to wcm

resourceDesignName

specific to wcm

currentStyleName

specific to wcm

Example:

<%@page session="false" contentType="text/html; charset=utf-8" %><%
%><%@ page import="com.day.cq.wcm.api.WCMMode" %><%
%><%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %><%
%><cq:defineObjects/>
[Note]Note

When the /libs/wcm/global.jsp file is included in the script, the <cq:defineObjects /> tag is automatically included.

<cq:requestURL>

The <cq:requestURL> tag writes the current request URL to the JspWriter. The two tags <cq:addParam> and <cq:removeParam> may be used inside the body of this tag to modify the current request URL before it is written.

It allows you to create links to the current page with varying parameters. For example, it enables you to transform the request:

mypage.html?mode=view&query=something into mypage.html?query=something.

The use of addParam or removeParam only changes the occurence of the given parameter, all other parameters are unaffected.

<cq:requestURL> does not have any attribute.

Examples:

<a href="<cq:requestURL><cq:removeParam name="language"/></cq:requestURL>">remove filter</a>
<a title="filter results" href="<cq:requestURL><cq:addParam name="language" value="${bucket.value}"/></cq:requestURL>">${label} (${bucket.count})</a>
<cq:addParam>

The <cq:addParam> tag adds a request parameter with the given name and value to the enclosing <cq:requestURL> tag.

It has the following attributes:

name

name of the parameter to be added

value

value of the parameter to be added

Example:

<a title="filter results" href="<cq:requestURL><cq:addParam name="language" value="${bucket.value}"/></cq:requestURL>">${label} (${bucket.count})</a>
<cq:removeParam>

The <cq:removeParam> tag removes a request parameter with the given name and value from the enclosing <cq:requestURL> tag. If no value is provided all parameters with the given name are removed.

It has the following attributes:

name

name of the parameter to be removed

Example:

<a href="<cq:requestURL><cq:removeParam name="language"/></cq:requestURL>">remove filter</a>

Sling Tag Library

The Sling tag library contains helpful Sling functions.

When you use the Sling Tag Library in your script, the script must start with the following code:

<%@ taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0" %>
[Note]Note

When the /libs/wcm/global.jsp file is included in the script, the sling taglib is automatically declared.

<sling:include>

The <sling:include> tag includes a resource into the current page.

It has the following attributes:

flush

A boolean defining whether to flush the output before including the target.

resource

The resource object to be included in the current request processing. Either resource or path must be specified. If both are specified, the resource takes precedence.

path

The path to the resource object to be included in the current request processing. If this path is relative it is appended to the path of the current resource whose script is including the given resource. Either resource or path must be specified. If both are specified, the resource takes precedence.

resourceType

The resource type of the resource to be included. If the resource type is set, the path must be the exact path to a resource object: in this case, adding parameters, selectors and extensions to the path is not supported.

If the resource to be included is specified with the path attribute that cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type.

replaceSelectors

When dispatching, the selectors are replaced with the value of this attribute.

addSelectors

When dispatching, the value of this attribute is added to the selectors.

replaceSuffix

When dispatching, the suffix is replaced by the value of this attribute.

[Note]Note

The resolution of the resource and the script that are included with the <sling:include> tag is the same as for a normal sling URL resolution. By default, the selectors, extension, etc. from the current request are used for the included script as well. They can be modified through the tag attributes: for example replaceSelectors="foo.bar" allows you to overwrite the selectors.

Examples:

<div class="item"><sling:include path="<%= pathtoinclude %>"/></div>
<sling:include resource="<%= par %>"/>
<sling:include addSelectors="spool"/>
<sling:include resource="<%= par %>" resourceType="<%= newType %>"/>
<sling:include replaceSelectors="content" />
<sling:defineObjects>

The <sling:defineObjects> tag exposes the following, regularly used, scripting objects which can be referenced by the developer:

slingRequest

SlingHttpServletRequest object, providing access to the HTTP request header information - extends the standard HttpServletRequest - and provides access to Sling-specific things like resource, path info, selector, etc.

slingResponse

SlingHttpServletResponse object, providing access for the HTTP response that is created by the server. This is currently the same as the HttpServletResponse from which it extends.

request

The standard JSP request object which is a pure HttpServletRequest.

response

The standard JSP response object which is a pure HttpServletResponse.

resourceResolver

The current ResourceResolver object. It is the same as slingRequest.getResourceResolver().

sling

A SlingScriptHelper object, containing convenience methods for scripts, mainly sling.include('/some/other/resource') for including the responses of other resources inside this response (eg. embedding header html snippets) and sling.getService(foo.bar.Service.class) to retrieve OSGi services available in Sling (Class notation depending on scripting language).

resource

the current Resource object to handle, depending on the URL of the request. It is the same as slingRequest.getResource().

currentNode

If the current resource points to a JCR node (which is typically the case in Sling), this gives direct access to the Node object. Otherwise this object is not defined.

log

Provides an SLF4J Logger for logging to the Sling log system from within scripts, eg. log.info("Executing my script").

It has the following attributes:

requestName

responseName

resourceName

nodeName

logName

resourceResolverName

slingName

Example:

<%@page session="false" %><%
%><%@page import="com.day.cq.wcm.foundation.forms.ValidationHelper"%><%
%><%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0" %><%
%><sling:defineObjects/>