Servlet Development Guide : PART III Programming : Chapter 6 The Servlet API : Implementing a Filter
Implementing a Filter
A typical filter implementation consists of three main steps:
The filter may process the incoming request.
The filter passes the processed request and response to the next object in the filter chain.
The filter may process the response before the filter returns.
The Servlet Specification defines init() and destroy() methods for a filter. The filter should allocate resources in the init() method and release resources in the destroy() method. The servlet container calls the filter init() method before sending any requests through the filter, and calls the destroy() method before removing the filter from service.
The outline below shows a minimal filter implementation:
 
#include <rwsf/servlet/Filter.h>
#include <rwsf/servlet/FilterChain.h>
#include <rwsf/servlet/ServletRequest.h>
#include <rwsf/servlet/ServletResponse.h>
 
RWSF_DEFINE_FILTER(SimpleFilter)
 
class SimpleFilter : public rwsf::Filter {
 
void
SimpleFilter::doFilter(rwsf::ServletRequest& request,
rwsf::ServletResponse& response,
rwsf::FilterChain* chain)
{
// ... process request
 
// pass the request on
chain->doFilter(request, response); //1
 
// ... process response
}
};
Line //1 dispatches request and response to the next filter in the filter chain. The chain forwards request and response to the doFilter() function of the next filter in the chain. Note that the chain->doFilter() call blocks until the doFilter() function on the next filter in the chain returns.
A filter must explicitly dispatch the request and response along the chain. This means that a filter can refuse to allow a request to reach a resource by returning without dispatching the request. If the filter does not dispatch the request along the chain, the response returns to the servlet container without reaching the original destination. For example, the code below shows a doFilter() function that limits access to a servlet:
 
void
myFilter::doFilter(rwsf::ServletRequest& request,
rwsf::ServletResponse& response,
rwsf::FilterChain* chain)
{
if (isAuthorized(request))
{
chain->doFilter(request, response);
}
else
{
rwsf::ServletContext context = getServletContext();
rwsf::RequestDispatcher unauthRD =
context.getNamedDispatcher("Unauthorized");
unauthRD.forward(request, response);
}
}
In the code above, the filter does not forward the request along the chain if authorization fails but, instead, redirects the request to a servlet that handles unauthorized requests. The original servlet never receives the request.