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 Filters, but consider the last sentence when deciding.
Some good use cases for Filter usage:
- transforming output produced by a JSP or Servlet
- injecting additional request parameters or attributes into an HTTP request
- injecting additional HTTP headers or cookies into a HTTP response
@SlingFilter(
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
*
*/
@Activate
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.
Enjoy!