SpringMVC拦截器简单使用
要点:SpringMVC中的拦截器只会拦截访问的控制器方法,自动过滤静态资源(即访问jsp/html/css/image/js是不会进行拦截的)
1.编写拦截器,实现HandlerInterceptor接口的方法
public class MyInterceptor implements HandlerInterceptor {
/**
* @return true:放行,执行下一个拦截器; false:不放行
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
2. SpringMVC中配置拦截器
<!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.cokebot.config.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
3. 示范Controller
@RequestMapping("/t1")
public String test() throws NoSuchMethodException {
System.err.println("TestController.test()方法执行了");
return "success";
}
4. 控制台输出
preHandle
TestController.test()方法执行了
postHandle
afterCompletion