What is a filter?
A filter is an optional component of a web application which is used to perform pre and post processing operations such as logging, validation, flow control etc. Filters are associated to the servlets and HTML pages of the applications. Whenever a request is received for these components, associated filter is invoked. The filter performs required pre processing and invokes the requested component. When the request is processed by the component, control is returned to the filter which performs the required post processing. Following diagram describes the flow of a request processing using filter.
Description of the diagram:
What is pre and post processing?
The tasks which are performed before and after the actual processing are called pre and post processing respectively. In a web application, we can have request processing logic in the form of servlets; Event processing logic in the form of listeners and common pre and post processing logic in the form of filters. To understand all these, lets take the following real life analogy:
Uses of a filter in a web application:
1. Logging: Keeping the record of something for future use is called logging. Logging is a common requirement of web applications especially where financial transactions are involved. Logging can be done in the following two ways:
a) Each static page need to be converted to a servlet so that its log can be maintained.
b) Invocation of the logging method from each servlet will create maintenance problem. If the logger method is changed in future, all the servlet need to be modified.
a) Log of static page can be maintained without converting them to servlet.
b) If the logger method is changed in future, only a single filter need to be modified.
2. Validation: The process of checking whether the input or output is correct or not is called validation. Validation is also a common requirement of web applications. Being common requirement, it must be implemented with the help of filters.
3. Flow Control: The process of managing the flow of requests in a web application is called flow control. You must have noticed in web sites such as facebook, gmail etc, if you directly send a request for a bookmarked page, you are redirected to the login page. Such functionality can be easily implemented with the help of a filter which act a single entry point of the application. The filter is associated to each static as well as dynamic page of the application which can only be viewed after login. Whenever a request is submitted for such a page, the filter is invoked which checks for the user session. If user session is found, request is forwarded to the page otherwise it is forwarded to the login page.
Similar to logging, validation and flow control any operation which is common for some or all requests should be implemented with the help of filters.