Filter is used for filtering the request and perform some action like authenticity of session, user is valid or not for that request, etc.
Servlet is used for performing the action which needs to be taken for particular request like user login, get the response based on user role, interacts with database for getting the data, business logic execution, etc.
Filter has different purpose and servlet has different purpose.
Joined: Mar 04, 2008
I know SUN added Filter for different propose from Servlet.
But a Filter can receive HTTP Request from a client and send HTTP Response back to the client.
Technically you can have some processes done in Filter and then send it right back to client w/o going through HTTPServlet or JSP.
I have never tried, but I think it is possible to have a web.xml that only have Filters (chain of filters) defined w/o any Servlet or JSP.
Will web container give any errors because of the web.xml?
Tejas Jain wrote:A servlet, with some helper classes, can do anything Filters are defined to do. SUN added Filter framework to Servlet in 2.3. I do not feel Filter is very useful.
Well filters work as wrappers to servlets. So they can intercept both incoming as well as outgoing requests, then we have chaining. How do you think this can be done in servlets? RequestDispatcher is not what I am asking here.
Finally there is something called as "Design Patterns". If your code does not follow/define standards, it does not exist ;).
@Tejas: Filter is suitable if one wants to modify/filter request based on some conditions. Servlet is useful when you want to control, preprocess and/or postprocess requests.
Filter is useful for following scenarios :
1)Query the request and act accordingly.
2)Block the request-and-response pair from passing any further.
3)Modify the request headers and data. You do this by providing a customized version of the request.
4)Modify the response headers and data. You do this by providing a customized version of the response.
5)Interact with external resources.
And one more thing, every component is defined for certain purpose and we cannot mix purpose of two component. In java, servlet is base for everything in JEE and one can do whatever one wants using servlet.