13

I'm writing a project for academic purposes which among other irrelevant stuff, includes writing a filter which monitors servlet/jsp response times.

The thing is that the filter should work on every deployed web application in the server and not only over a specific one, I just couldn't find any information regarding applying "global" filters.

Is it even possible?

NOTE: It's important to mention that i'm using Apache Tomcat 7 as the server of choice.

Thanks!

Mikey

Mikey S.
  • 3,301
  • 6
  • 36
  • 55

3 Answers3

20

You could provide the filter in Tomcat's common classpath and edit Tomcat's own /conf/web.xml to add the filter, but this does not run on non-existing webapp contexts (i.e. it does not cover all possible requests) and it is overrideable in all deployed webapps. The more robust solution depends on the servlet container used. In case of Tomcat, you need the Valve component.

Kickoff example:

import org.apache.catalina.valves.ValveBase;

public class MyValve extends ValveBase {

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        // ...

        getNext().invoke(request, response);
    }

}

register it as follows in server.xml:

<Valve className="com.example.MyValve" />
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • What about adding the right declarations in the tomcat /conf/web.xml? will that work? – Mikey S. Oct 03 '11 at 13:32
  • Can also. They're only overridable whenever webapp's `/WEB-INF/web.xml` has another one with same filter name. If you can afford this risk, go ahead with putting it in Tomcat's `/conf/web.xml`. Valves are in no way overridable/disableable from the webapp side on. – BalusC Oct 03 '11 at 13:51
  • Last question - where should the compiled Filter code be placed using either one of the above methods (valve or filter)? – Mikey S. Oct 03 '11 at 15:31
  • 1
    In the common classpath of Tomcat. Either just as JAR straight in `Tomcat/lib` or in a path as represented by `common.loader` property in `/conf/catalina.properties`. – BalusC Oct 03 '11 at 15:39
  • From my expirience filter declared in conf/web.xml are executed AFTER all filters defined in webapp – Sergey Ponomarev Jul 09 '18 at 14:37
0

Filters are configured per-web app, but Tomcat itself may have a mechanism for timing request/response processing times.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
-2

You can config the url-pattern of your filter to process any request/response that you want. Please check http://www.caucho.com/resin-3.0/config/webapp.xtp#filter-mapping

ControlPower
  • 610
  • 4
  • 7
  • Sorry, this does not answer the OP's question at all. He specifically mentioned that he wanted something that would apply to all webapps on a given Servlet container. – Dan Oct 03 '11 at 02:17