Search code examples
jakarta-eeannotationsjava-ee-6servlet-filters

JavaEE6 enable / disable webfilter without recompile


I'm migrate application to the new JavaEE6 standard. And annotation is very easy to use when creating new filters. I only need to add a @WebFilter annotation to my POJO classes and it works well.

What confused me is: all filters with the annotation would be automatically loaded by the container. This is not desired sometimes. I may create a set of filters and different webapp would choose to use only subset of these filters. So the question I have: is there an easy way to enable / disable filters based on different deployment, while still allow me to use the simple WebFilter annotation for each filter class?

I found this article when searching on this top: Dynamically registering WebFilter with Java EE 6

But this article seems to suggest not using annotations on each filter class, and load them via a ServletContextListener directly referencing each filter class. It doesn't seem to be an optimal solution.

Thank you,


Solution

  • That's not possible.

    Your best bet is to extend the filters with a check on some web.xml context param, or a VM argument, or an environment variable which indicates that the filter should not be used.

    E.g.

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ("true".equals(System.getProperty("com.example.DISABLE_FILTER"))) {
            chain.doFilter(request, response);
            return;
        }
    
        // Original filter code here.
    }
    

    which can be disabled by supplying VM argument -Dcom.example.DISABLE_FILTER=true.