Apache Tomcat Valves, Custom Valve

Valves in Apache Tomcat allow inserting logic into the request processing pipeline before the request reaches the application. They function at the server level, similar to how filters work at the application level, though they can be tied to a specific context root.

Common use cases for valves include Single Sign-On (SSO) and authentication, with AccessLogValve being a well-known example.

A custom valve can be implemented by extending ValveBase and overriding the invoke method:

import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

public class CustomValve extends ValveBase {
   
    @Override
    public void invoke(Request request, Response response) throws IOException,
    ServletException {
        try {
        //if you want to add something to request
        request.getCoyoteRequest().getMimeHeaders().setValue("somekey").setString(somevalue);
            getNext().invoke(request, response);
        } finally {
            //TODO cleanup
        }
    }

}

After implementation, the valve needs to be registered in the server runtime, typically via an application deployment descriptor. For example, in JBoss, this can be done in jboss-web.xml:

<jboss-web>
    <context-root>/</context-root>
    <valve>
      <class-name>CustomValve</class-name>
    </valve>
</jboss-web>

This configuration maps the CustomValve to the application's context root.

Comments (0)

Loading comments...