I\'m researching this so that I can respond better in interviews. I\'ve been searching around for a clear and concise answer.
So far, and by all means correct me if I a
Filters:
Interceptors:
excludeMethods
or includeMethods
.Filters are from Servlet API and Interceptors are from Struts 2 , Difference comes when we talk about web applications and enterprise apps, filter is used only in web applications whereas interceptor can be used with web as well as enterprise applications. Life cycle methods of both, also differs.
The interceptor stack fires on every request. filters only apply to the urls for which they are defined. you use one or the other depending on need. Lets say you need to verify a cookie is present for every request. Use an interceptor. Lets say that you need to pop up an external app on some requests (driven by a url), use a filter.
In one of the interview I answered this question like,
Interceptors are struts2 concept and application developer has control over it. Also, It works withing struts2 application boundary and it has access to Actions, ValueStack and other objects along with Struts2 goodies.
While Filter is more suitable for deployment time configurations. It has limited access to application, And in most cases its generic for most of the web-app deployed in server.
If logic in code is more coupled with Application, its better suited for interceptor or else if its infrastructure, we can place it in servlet filter.
I think the first point is the answer, but you should probably be able to say more than just
interceptors are in struts 2 and filters are part of the Servlet API
In fact, as an interviewer, I would be expecting and hoping to here you explain exactly what the difference between the Servelt API and a web application framework, like Struts 2 is. This is actually a chance to show your understanding of the entire Java web app ecosystem and infrastructure.
Good answers might touch upon:
How the Struts 2 framework is implemented within a Servlet Filter.
What specific use cases would call for a servlet filter outside of struts 2 but within the same web application?
What indeed is the Servlet API, a web application, a web application framework, etc.?
Answering in way that showed your understanding of all of these topics is what there looking for, I would guess.