Search code examples
servlet-filterstomcat8

How can I programatically obtain a servlet filter instance?


I have a class MyFilter which implements javax.servlet.Filter. Tomcat creates a single instance of this based on the web.xml configuration. The filter collects statistics about all requests (since application start) and stores them in member variables.

I wish to display these statistics on a web page. How can I obtain the instance of MyFilter which was created by Tomcat?


Solution

  • Quoting from the documentation:

    Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use.

    Why do not you store the data you need in ServletContext attributes? You can store the filter as follows:

    @Override
    public void init(FilterConfig config) throws ServletException
    {
        // Store our instance in the servlet context for usage by servlets.
        ServletContext context = config.getServletContext();
        context.setAttribute("MyFilter", this);
    }
    

    And then in the servlet with the same context:

    Filter filter = (Filter) getServletContext().getAttribute("MyFilter");