Wednesday, September 13, 2017

Global custom filter in Apache Tomcat

We are aware about custom filters and built in filters available in Apache Tomcat.
If we are writing a custom java filter in our project, it will be look like follows,

public class MyFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //your custom filter or set custom response header here
        chain.doFilter(request, response);
This custom filter can help us to track and filter all requests coming to our webappliation, but it can not act like a global filter for all webapplications hosted in Apache Tomcat.

Apache Tomcat supports custom Valve elements which can help us to make this happen.

Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (EngineHost, or Context)

Following are the steps to implement a custom Valve in Apache Tomcat:

  1. Create a Maven Java Application.
  2. Add the following dependency:
<!-- --><dependency> <groupId>org.apache.tomcat</groupId> <artifactId>catalina</artifactId> <version>6.0.53</version> <scope>provided</scope></dependency>
  1. Create your Java class and extend it from ValveBase.
  2. Implement the invoke(Request, Response) method.
  3. import org.apache.catalina.valves.ValveBase;
    public class GlobalFilterValve extends ValveBase {
        public void invoke(Request request, Response response) throws IOException, ServletException {
            //Do your filter/setting header in response here
            getNext().invoke(request, response);
  4. Build your library (.jar) file
  5. Copy the jar file in the ${tomcat.home}/lib directory.
  6. Configure the server.xml to use your new valve. For example:
<valve className="org.devan.MyValve"/>
  1. Start the server to see your new valve in action

Thank you !!!

No comments:

Post a Comment

Total Pageviews