Creating a Java Web Application Filter

Just a simple note to demonstrate this.

Create a source file that implements

This interface provides three methods:

The init method is called just once by the web container (e.g. Tomcat) to register the filter. Any setup should be done here, for example, setting member variables.

The destroy method is called just once by the web container when it takes the filter out of service.

The doFilter method is called upon each page load (page load that matches the filter configuration. More on this immediately below) The request and response objects are passed in. The Filter chain is effectively the next Filter. After processing in the current filter,

should be called to invoke the next filter.

More information here in the Java Docs

HttpServletRequest and HttpServeltResponse can always be obtained by casting.

 

The filter must be be setup in web.xml as so.

Any number of filters can be defined here. The order in which they are defined here is the order in which they appear in the filter chain (javax.servlet.FilterChain).

Comments welcome…..