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,
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
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.
A Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (Engine, Host, or Context)
Following are the steps to implement a custom Valve in Apache Tomcat:
- Create a Maven Java Application.
- Add the following dependency:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/catalina -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>catalina</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
- Create your Java class and extend it from
ValveBase
. - Implement the
invoke(Request, Response)
method. import org.apache.catalina.valves.ValveBase; public class GlobalFilterValve extends ValveBase { @Override public void invoke(Request request, Response response) throws IOException, ServletException { //Do your filter/setting header in response here getNext().invoke(request, response); } }
- Build your library (
.jar
) file - Copy the jar file in the
${tomcat.home}/lib
directory. - Configure the
server.xml
to use your new valve. For example:
<valve className="org.devan.MyValve"/>
- Start the server to see your new valve in action
Thank you !!!
No comments:
Post a Comment