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;