![]() |
![]() |
||||
At line 5 added 15 lines. |
A filter is run before servlets or JSP pages get called, so it's possible to "chain" 1 or more filters before the final servlet/page is hit. |
The main advantage is that it can sit outside the application, and is a stand-alone module. You can find many free filters on the internet. |
!Example Uses |
* Add headers to the response (eg: HSTS headers if using SSL, or Locale-specific headers) |
* Log requests to a database |
* Block requests, based on the URL or the HTTP headers |
* Dump HTTP headers to a file for examination/debugging |
* Modify the request before it hits the rest of the application. As an example, we recently wrote a filter for a customer which translates paths such as __/Events__ into URL parameters such as __?pageId=42__ based on a lookup table in their database. This was written as a filter to avoid modifying their existing application. The filter is run first, so it is able to intercept the requests in this way and modify them. Their application still responds as usual to ?pageId=42, but now they can use URLs on their pamphlets such as http://domainname.com/Events and it will go the same page (and show in the URL bar in the browser). |
!Basic Use of Filters |
* If your filter decides to modify the request, construct a new URL and call {{{config.getServletContext().getRequestDispatcher(finalPath).forward(req, res);}}} |
* If your filter decides to pass the request down the chain, after optionally adding headers, logging trace information, or performing some other action, call {{{filterchain.doFilter(req, res)}}}; |