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.
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:Technically you can have some processes done in Filter and then send it right back to client w/o going through HTTPServlet or JSP.
Technically, you can also bang in a screw with a hammer, but it's a poor tool for the job.
Use the right tool for the job. Just because you can use the wrong tool to get a job done doesn't mean that you should.
SUN (including open sources) used to like to create many different APIs to do same simple tasks in different ways. This might be one of the reason of SUNdown.
Bear, I like your picture. I actually saw someone did it. At least, it is quicker with just one bang... Are you from Yellow Stone.
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 ;).
Hope that helps
Tejas Jain wrote:A servlet, with some helper classes, can do anything Filters are defined to do.
I would be interested to see how you could use a servlet to do something like, for example, using XSLT to transform the output of another servlet as in this tutorial.
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 for more information about filter, check following link : http://www.oracle.com/technetwork/java/filters-137243.html
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.