欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Filter Interceptor

程序员文章站 2022-07-15 15:38:49
...

Filter

public class CustomFilter implements javax.servlet.Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//before
		chain.doFilter(request, response);
       //after
	}

	@Override
	public void destroy() {

	}


}

Interceptor

import org.springframework.web.servlet.HandlerInterceptor;
//第一种 实现接口
public class CustomInterceptor implements HandlerInterceptor {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		return false;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//第二种继承Adaptor
public class CustomInterceptor2 extends HandlerInterceptorAdapter {

}

interceptor配置

<mvc:interceptors>  
    <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->  
    <bean class="com.host.app.web.interceptor.AllInterceptor"/>  
    <mvc:interceptor>  
        <mvc:mapping path="/test/number.do"/>  
        <!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->  
        <bean class="com.host.app.web.interceptor.LoginInterceptor"/>  
    </mvc:interceptor>  
</mvc:interceptors>  

 

执行顺序

Filter.doFilter -->Filter.chain.doFilter() --> Interceptor.preHandle-->

Controller.execute-->

Interceptor.postHandle-->Controller.response-->

Interceptor.afterCompletion-->Filter.chain.doFilter() after;

转载于:https://my.oschina.net/svili/blog/886477