定义拦截器
public class MyInter1 implements HandlerInterceptor{
//主要逻辑:在handler之前执行:抽取handler中的冗余代码
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("pre~~~");
/*
response.sendRedirect("/springMVC_day2/index.jsp");//响应
return false;//中断请求
*/
return true;//放行,后续的拦截器或handler就会执行
}
//在handler之后执行:进一步的响应定制
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("post~~");
}
//在页面渲染完毕之后,执行:资源回收
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("after~~");
}
}
配置拦截路径
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/inter/test1"/>
<mvc:mapping path="/inter/test2"/>
<mvc:mapping path="/inter/test*"/> <!-- test开头 -->
<mvc:mapping path="/inter/**"/> <!-- /** 任意多级任意路径 -->
<mvc:exclude-mapping path="/inter/a/**"/> <!--不拦截此路径-->
<bean class="com.baizhi.interceptor.MyInter1"></bean> <!--拦截器类-->
</mvc:interceptor>
</mvc:interceptors>