HandlerInterceptor-和-Filter.md

简书迁移

Posted by thrfox on June 29, 2020

首先,一张图可以清晰的表示之间的关系 image.png Filter的运行是依赖于Servlet容器的,与spring框架没有关系,init与destory只在servletContext阶段执行 而HandlerInterceptor是基于于WebApplicationContext,在WebApplicationContext内的controller可以多次调用 image.png 即ServletContext大于WebApplicationContext

1
2
3
4
5
6
7
public interface Filter {
    public void init(FilterConfig filterConfig) throws ServletException;
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException;
    public void destroy();
}
1
2
3
4
5
6
7
8
9
public interface HandlerInterceptor {
	boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	    throws Exception;
	void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception;
	void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception;

}