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

Jérôme Verstrynge picture Jérôme Verstrynge · Sep 26, 2011 · Viewed 12.5k times · Source

As part of exploring/learning Struts2, JSP and Servlets, I see from here and there that servlets and servlets-mapping can be used in web.xml. However, Struts2 mentions filters and filter-mapping too for web.xml.

What is the difference between both? Are these mutually exclusive? When should I use which and why? Can someone clarify the concepts? Thanks.

CLARIFICATION

I just got to understand that I needed to understand how Struts2 and Servlets are related: http://www.coderanch.com/t/57899/Struts/Difference-between-servlet-struts

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Sep 26, 2011

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.