Having a web framework handle requests from single point of entry is a solved problem. However, should that single point of entry be a Filter or a Servlet? Why would a web application developer prefer one over the other? Why would a framework developer prefer one over the other?
Filter provides functionality which can be “attached” to any web resource. Servlet used for performing action which needs for particular request as user login, get response based on user role, interacts with database for getting data, business logic execution, and more.
Servlets and JSPs The Servlet and JSP are incredibly simple ways to handle an incoming request, and to develop HTML that gets displayed inside a client's web browser, respectively. All the existing Java-based web frameworks simply build on top of the Servlet and JSP API.
Java Servlet Filter is used to intercept the client request and do some pre-processing. It can also intercept the response and do post-processing before sending to the client in web application.
Most Java web frameworks, including Spring MVC, use servlets behind the scenes. You CAN use servlets to write a web application, but you'll have to handle all of the details manually.
Let's look how existing frameworks do it:
That were the most popular frameworks. There are more, but most of them use a Servlet.
Most if not all servlets are supposed to be mapped on a suffix URL pattern, for example *.jsf
(JSF), *.html
(Spring), *.do
(Struts), etc. This enables the developer to easily ignore resources which are not of interest. So the advantage of the Filter of being able to do that disappears. Only Wicket used to have the need to be mapped on an extra path /app/*
and the change of Servlet to Filter in Wicket 1.3 was done with the sole argument that you will be able to map it on just /*
. This however adds extra configuration boilerplate in order to be able to ignore static resources. I personally don't understand why they didn't just use a suffix mapping.
All web frameworks rely on HTTP requests. In a Servlet it's already available straight in the standard methods (often just the service()
method is been used). In a Filter you would need to cast it back (although this is not necessarily expensive).
Also, Sun/Oracle has made a distinct separation between Filters and Servlets on the following grounds: When you want to filter requests/responses on certain conditions, use a Filter. When you want to control requests/responses and/or create responses, use a Servlet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With