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
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.
What is servlet mapping? Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to.
A filter mapping matches a filter to a web component by name, or to web resources by URL pattern. The filters are invoked in the order in which filter mappings appear in the filter mapping list of a WAR.
The filter-mapping element maps a URL pattern or servlet name to an instance of a filter. The filter-mapping always contains a filter-name element and a url-pattern element. The filter-name element must match a filter-name defined in a filter element elsewhere in the web. xml file.
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.
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