AEM \ CQ5 Sling Filters

Posted in AEM Tutorials By Raj On February 23, 2017


In Adobe Experience Manager ( AEM )  the Sling Filters are OSGI Services which are implementing from standard servlet filter ( javax.servlet.Filter ) and we need to register this as service using sling filter annotations, we can use AEM sling filters to call a servlet, to redirect to another page, to authenticate request, preprocess and post processing etc…, in this article, I am going to explain how can we use sling filters to redirect to another page based on certain conditions

We need to register two service properties to successfully execute filters which are sling.filter.scope and service.ranking

sling.filter.scope -> this is a required field, if we don’t specify this then the sling filter will not fire, so we must assign filter chain to this, the sling maintains five filter chains REQUEST, INCLUDE, FORWARD, ERROR, and COMPONENT, refer servlet filter support to get more information on filter chains

service.ranking ->  we need to specify integer values to this, the higher number will give more priority to the filter chain

Filter interface

The init method will be used to initialize values

Get data in Filter

The doFilter will be invoked every time when user make a request to the resource, the main business logic such as filtering tasks etc… should go here, in this article, I am fetching resource object from the slingRequest and checking the resourceType, if the resourceType is cq:page then adapt the resource object to page manager and read the template path, if the template path equals to redirect template then redirect to home page

The destroy method will be invoked only once when the filtering is taken out of service