A filter can be used for access control, compression and some other tasks. However I can also use a servlet that provides access control and after that forwards the request to the intended servlet. Again a servlet can receive the response from a servlet and can perform the compression before sending the data to the clien. If all that I can do with a servlet, then why do need Filters. I mean what is that a filter can do, that a servlet cannot.
Joined: Jun 19, 2001
with a filter you can apply access control and/or compression (and so on) BEFORE the request gets handled by a servlet or BEFORE the response gets sent back to the client.
request from client -> security filter -> servlet -> compression filter -> response to client.
if you want to achieve this with servlets, then you would need to add the security/compression code to all of your servlets.
However I can also use a servlet that provides access control and after that forwards the request to the intended servlet
This is handled for you in a Filter. Yes, a FilterServlet is really just a Servlet but it handles a bit of menial tasks for you automatically. Depending on your mapping, all requests will go through the filter first.
What you are eluding to in what you could manually do with a Servlet is create a Controller Servlet. In your View's all your requests will need to be sent to the Controller Servlet which then determines where the request goes. Unless you use a Framework, you would need to code this manually.
Using a ServletFilter just saves you a bit of manual labor really and provides a single point of entry for your security/compression/logging, etc.
Joined: Dec 23, 2003
There are two main things I consider when deciding between a Filter and a Servlet.
Second, do I need to be able to 'plug' this into any URL-Mapping in any order? With a Servlet you must know the URL to plug into. The first servlet that gets control of the request also gets the responsibility of determining where to go when it's done. With a Filter the container is able to manage where to go next (the Chain) and the develop only need call Chain.doFilter() to notify the container it is done it's work. With a Servlet you must provide the URL to forward to. This really adds a lot of work to development if you have to have that ability with a servlet.