A filter can be applied to one or more servlet/JSP files. A filter is an object that can transform a request or modify a response. It can preprocess a request BEFORE it reaches a servlet and it can preprocess a response after it leaves the servlet.
A client sends a request
The filter intercepts the client request
The filter examines and can modify the request header and request data by using its own custom request to wrap araond the intercepted request object
the filter propagates the request to the servlet
the servlet generates a response a flushes it.
the filter intercepts the response
the filter can modify the headers and data by using its own custom response
Once completed, the filter sends the newly filtered response to the client
A filter must implement the javax.servlet.Filter interface. Let's say we create a filter.
then in your web.xml file
after this you can either filter specific servlets or URL patterns specific servlet