SlingFilter Addendum

SlingFilter Addendum

One thing to keep in mind about Filters, their removal should not render your system unusable. For example, the ICS Filter in my last article, if I remove or disable it, the ICalExportServlet continues to function (as well as the rest of CQ) without error. I would say if your application does not function without the functionality you are writing, then a Filter is probably the wrong animal for you.  You could write alot of things as Filtersbut consider the last sentence when deciding.  

Some good use cases for Filter usage:

  1. transforming output produced by a JSP or Servlet
  2. injecting additional request parameters or attributes into an HTTP request
  3. injecting additional HTTP headers or cookies into a HTTP response
Another thing to consider is the amount of processing time your proposed Filter will consume.  The work you do should be a small, and not time prohibitive.  What happens when your service gets hit with 1k, 2k, xk requests?  If processing time is much longer than 10's of milliseconds then maybe a Filter isn't the best fit.
Another best practise is to enable, and expose metadata to the OSGi container, specifically a Boolean value to Enable/Disable the Filter.  The following will expose the Boolean value to the Apache Felix Console. This will allow you to enable / disabled it on the fly.  Keep in mind, there is no "magic" in simply defining this stuff.  You still have to code your Filter such that it "honors" the Boolean value.  When 'FALSE', it should simply invoke 'chain.doFilter(request, response)'.
public final MyFineFilter implements javax.servlet.Filter {
* Enable/Disable The Filter
@Property(name="enabled", label="Enable Filter",
description="Enables or Disabled the Filter",
boolValue = true)
private Boolean enabled;
* OSGi LifeCycle Methods
protected void activate(ComponentContext context) {
Dictionary props = context.getProperties();

enabled = PropertiesUtil.toBoolean(props.get("enabled"), true);

LOG.trace("{} activated", this.getClass().getName());

I guarantee you that at least once in your applications lifetime, you will want to disable it to troubleshoot an issue.  You will want your Filter "out of the way" to rule that out as a possible problem causing your issue.

One more passing warning.  If you wrap the Request or Response, extend or use the Sling Request and Response wrappers instead of the Servlet API ones.  Remember, you are writing this for Sling/CQ - which expects a SlingHttpServletRequest/Response.  Without that, you will break Asimov's first rule (roughly): Do no harm.


Share this post


comments powered by Disqus