依赖于servlet容器。在实现上基于函数回调。 优点:可以对几乎所有请求进行过滤。 缺点:一个过滤器实例只能在容器初始化时调用一次。 使用过滤器的目的是用来做一些过滤操作,获取我们想要获取的数据,比如:在过滤器中修改字符编码;在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等。 例如spring-shiro.xml中配置的自定义过滤器,可以过滤拦截所有类型的请求。
<!--自定义filterChainDefinitionMap --> <bean id="chainDefinitionSectionMetaSource" class="com.gzsolartech.smartforms.shiro.ChainDefinitionSectionMetaSource"> <property name="filterChainDefinitions"> <value> /scripts/** = anon /styles/** = anon /images/** = anon /api/** = anon /resources/** = anon /console/bpm/taskInfo/push.xsp= anon /ibm_security_logout**= anon /IT22/getData.xsp= anon /PD00004Controller/createDocument.action= anon /pd00002/operation/createDocument.action= anon /console/form/refresh/initialized.action= anon /console/bpm/taskInfo/pullOrigMsg.xsp= anon /services/**= anon /console/bpm/adminact/combinetoken/**.xsp= anon /console/login.xsp = anon /console/dmn/** = anon /console/user/login.action=anon </value> </property> </bean>依赖于web框架,在SpringMVC中就是依赖于SpringMVC框架。在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。 优点:由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个controller生命周期之内可以多次调用。 缺点:只能对controller请求进行拦截,对其他的一些比如直接访问静态资源的请求则没办法进行拦截处理。 比如在springmvc中springmvc.xml配置拦截器interceptors
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.it.controller" /> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 资源映射 --> <mvc:resources location="/WEB-INF/static/" mapping="/static/**"/> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/indexHomePage/**"/> <bean class="com.it.interceptors.UserLoginHandlerInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans>只要访问/indexHomePage/**开头的任何路径 就会进入com.it.interceptors.UserLoginHandlerInterceptor这个类进行拦截!
①拦截器是基于java的反射机制,而过滤器是基于函数回调。 ②拦截器依赖web框架,过滤器依赖servlet容器。 ③拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。 ④拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。 ⑤在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。 ⑥拦截器可以获取IOC容器中的各个bean,而过滤器就不行,在拦截器里注入一个service,可以调用业务逻辑。
参考文章 https://www.cnblogs.com/panxuejun/p/7715917.html https://www.jianshu.com/p/7bd0cad17f23
