Difference between servlet/servlet-mapping and filter/filter-mapping?

Servlet filters implement intercepting filter pattern. While servlet is the ultimate target of web request, each request goes through a series of filters. Every filter can modify the request before passing it further or response after receiving it back from the servlet. It can even abstain from passing the request further and handle it completely just like servlet (not uncommon). For instance caching filter can return result without calling the actual servlet.


Filters are used like Servlet Filters. For example, if you need to do security checks on certain URLs then you can add a filter for those pages. For instance, you can say /secure/pages/*.do needs to be intercepted by securityFilter. Then the doFilter() method of the SecurityFilter class (a class that implements the Filter interface) will handle the security audit before forwarding it to the actual requesting servlet.

Servlets are pretty much the standard stuff. You define a servlet and then let the servlet container know what type of requests needs to be mapped to that servlet.

They are not mutually exclusive. They both can be used at the same time. Think of filter like the way the word means - it "filters" things (logging, security,etc) before proceeding to the next servlet/action.