What is Filter in real world ?
- The literal meaning of Filter “a porous device for removing impurities or solid particles from a liquid or gas passed through it.”
- In our day to day activities we generally come across filter nomenclature like Oil filter, Air filter (Bike or Car), water filter or electronic filters (low pass filter, high pass filter etc.).
- So, filters are intelligent devices, which performs some sort of processing (on the input, which they receive), specifically to remove unwanted impurities components, from the input (or modify some attributes of input).
Purpose of filters in a enterprise applications (java):
Web application filters are same as that of real time filters. The web application is nothing but the component, which also deals with request (input) and response (output). The filter in web application can intercepts both request and response. Typically filter can be used for following kind of operations
- Validation of Request (some of examples are)
- Validating header of http request
- Validate the credentials of request (authentication of user name and password)
- Validation of entity stream (Like check the size of file, search some parameter in stream etc.)
- Modification of request (Add some header for all request or remove some header etc.)
- Encrypt- decrypt the request
- Logging etc.
Request response flow in a typical web applications:
These are few functions/things we can achieve with Filters. We can intercept both request and response, we can perform the actions as per our use case scenario.
We have introduced 3 filters (Filter 1, Filter 2 & Filter 3). The request response flow is shown in Fig 1 is as follows:
- The service client raises a request
- Request reaches the host (where our service is deployed)
- Filter 1 intercepts the request, perform the operation
- then, call dofilter (next filter in chain) method
- Request reaches Filter 2, perform the operation
- then, call dofilter (next filter in chain) method
- Similarly for Filter 3
- Finally request reaches to service
- service completes it task
- generate the response
- Response reaches Filter 3.
- Filter 3 can perform any operation on response
- Similarly response reaches Filter 2 -> Filter 1-> Response Sent back to Service client
We have discussed about the application of filter in post Create the logging filter in java using jersey framework.