A typical filter implementation consists of three main steps:
The filter may process the incoming request and response.
The filter passes the processed request and response to the next object in the filter chain.
The filter may process the request and 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> class MyFilter : public rwsf::Filter { void doFilter(rwsf::ServletRequest& request, rwsf::ServletResponse& response, rwsf::FilterChain* chain) { // ... process request // pass the request and response along the filter chain chain->doFilter(request, response); //1 // ... process response } }; RWSF_DEFINE_FILTER(MyFilter)
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.
© Copyright Rogue Wave Software, Inc. All Rights Reserved. All Rights Reserved. Rogue Wave is a registered trademark of Rogue Wave Software, Inc. in the United States and other countries. HydraExpress is a trademark of Rogue Wave Software, Inc. All other trademarks are the property of their respective owners.
Contact Rogue Wave about documentation or support issues.