Component Filtering with HstComponentWindowFilter
On this page
Introduction
Goal
Apply a filter to the page component hierarchy for certain requests.
Use Case
Assume you have the use case that based on some criteria, for example whether the visitor is authenticated or not, you want to show or hide certain components (blocks) from a page. Assume this very www.onehippo.org as example, and that you do not want to show the Hippo Developer Training component for authenticated visitors. Assume the page configuration used extends from base and looks like :
You can write code in every component its class (controller) that does some checks, like whether a visitor is authenticated, and for example if so, have the renderer output nothing. The downside is that the components still have their controller (java class) and view (jsp/freemarker template) invoked.
There is a way more elegant and flexible solution to achieve the above, which effectively just removes any component completely from the tree of components for a single request.
HstComponentWindowFilter Interface
HstComponentWindowFilter is an interface in the HST API that can be used to achieve the above requirement. It looks as follows:
Note from javadoc above the subtle difference between returning from doFilter:
- null
- The HstComponentWindow window after invoking window.setVisible(false)
Example Implementation
Below is an example implementation of HstComponentWindowFilter that checks whether there is a component parameter hide-for-authenticated-users = true, and if there is one, and the visitor is authenticated, the component gets completely skipped:
Inject the Filter in the Request Processing
After you have implemented your HstComponentWindowFilter you need to add some Spring configuration in your META-INF/hst-assembly/overrides to make sure the filtering is applied:
This is all, now you have your custom component filtering enabled.