Some time ago to participate in a project, filter used by the interceptor feel more than before using a lot of filter, now take out to compare
Filter
The method of the filter is to create a class Xxxfilter implement this interface, declare the filtering rule in the Dofilter method in the class, and then declare the path that he filtered in the configuration file Web.xml
<filter>
<filter-name>XXXFilter</filter-name>
<filter-class>
Com.web.util.XXXFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>XXXFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
Interceptor
The method of this filter is also to create a class xxxinterceptor implement this interface, in which intercept method write filter rules, but it filters the path of the method and filter, it is used in conjunction with the Strut.xml,
Creates a strus.xml struts-l99-default.xml that inherits Struts-default from Struts2, which is the parent of other child configuration files that are filtered as long as the path declared by the configuration file that inherits from the file. As follows
<package name= "Xxx-default" namespace= "/" extends= "Struts-default" >
<interceptors>
<interceptor name= "Authentication" class= "Com.util.XXXInterceptor"/>
<interceptor-stack name= "User" >
<interceptor-ref name= "Defaultstack"/>
<interceptor-ref name= "Authentication"/>
</interceptor-stack>
<interceptor-stack name= "User-submit" >
<interceptor-ref name= "User"/>
<interceptor-ref name= "token"/>
</interceptor-stack>
<interceptor-stack name= "Guest" >
<interceptor-ref name= "Defaultstack"/>
</interceptor-stack>
<interceptor-stack name= "Guest-submit"
< Interceptor-ref name= "Defaultstack"/>
<interceptor-ref name= "token"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name= "user"/>
</package>
Comparison first, filter is based on a callback function, The Dofilter method in the filter interface we need to implement is the callback function, and interceptor is based on the reflection mechanism of the Java itself, which is the most essential difference between the two.
Comparison second, filter is dependent on the servlet container, which can only be performed in the servlet container, and it is clear that there is no servlet container to adjust the Dofilter method back and forth. Interceptor is not related to the servlet container.
Comparison third, filter filtering range than interceptor, filter in addition to the filter request through wildcards can protect pages, pictures, files and so on, and interceptor can only filter requests.
Comparison fourth, filter exceptions for filter are generally declared at the time of loading in the Init method, and interceptor can be filtered by whether the XML declaration is a guest request or a user request.