CQ Tips and Tricks #3 – Getting a service from JSP

This is just a quick little example of my two favorite ways to grab a service in a JSP page.

adaptTo is super handy

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

<%@ page session="false" import="com.day.cq.security.UserManager"%>

<%
    UserManager userManager = resource.adaptTo(UserManager.class);
%>

see this page for more details on Adaptors make sure what your trying to adaptTo is mapped correctly. For example in this case I went from Resource to UserManager not all classes support AdaptTo.

Another simple way it to get a service is using the slingScriptHelper

<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%>
<sling:defineObjects />
<%@ page session="false" import="com.day.cq.contentsync.handler.util.RequestResponseFactory"%>

<%
    RequestResponseFactory requestResponseFactory = sling.getService(RequestResponseFactory.class);
%>

Comments are closed.