前言:通过案例,总结一下spring拦截器和过滤器
过滤器
过滤器依赖于serlvet容器,在容器初始化时生成实例,用于过滤操作,如统一修改字符编码、过滤低俗文字、XSS等危险字符
框架Filter
直接声明配置即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter>
<filter-mapping> <filter-name>encoding</filter-name> <servlet-name>/*</servlet-name> </filter-mapping>
|
自定义Filter
过滤器,实现javax.servlet.Filter接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
@Slf4j public class MyFilter1 implements Filter {
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { log.info("MyFilter1 start"); filterChain.doFilter(servletRequest, servletResponse); log.info("MyFilter1 end"); } }
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <!-- 自定义过滤器:myFilter1 --> <filter> <filter-name>myFilter1</filter-name> <filter-class>com.husky.ssm.common.filter.MyFilter1</filter-class> </filter> <!-- 自定义过滤器:myFilter2 --> <filter> <filter-name>myFilter2</filter-name> <filter-class>com.husky.ssm.common.filter.MyFilter2</filter-class> </filter>
<filter-mapping> <filter-name>myFilter1</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>myFilter2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
拦截器
拦截器依赖于web框架,基于Java反射,属于AOP的一种应用,只能对controller请求进行拦截,无法处理访问静态资源的请求
springmvc中,拦截器实现HandlerInterceptor的prehandle、postHandle、afterHandle方法
拦截器案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
@Slf4j public class MyInterceptor1 implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("MyInterceptor1 preHandle"); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { log.info("MyInterceptor1 postHandle"); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { log.info("MyInterceptor1 afterCompletion"); } }
|
配置
1 2 3 4 5 6 7 8 9 10
| <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean id="myInterceptor1" class="com.husky.ssm.common.interceptor.MyInterceptor1"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean id="myInterceptor2" class="com.husky.ssm.common.interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors>
|
执行顺序
过滤器——拦截器pre——controller业务逻辑——拦截器post——拦截器after——过滤器
多个过滤器执行顺序依照配置中的顺序
多个拦截器执行顺序依照配置中的顺序
总结