SpringMVC拦截器
本文最后更新于:5 天前
SpringMVC拦截器Interceptor
1、SpringMVC拦截器用于对控制其方法进行前置、后置处理
2、拦截器的底层实现技术是AOP
3、拦截器必须实现HandlerInterceptor
接口
使用场景
权限控制、登录拦截、字符集管理、国际化等,可以做到不修改原始代码的情况下实现功能。
例子
配置文件 applicationContext.xml
1 2 3 4 5 6 7 8
| <beans ...> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="MyInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans>
|
实现HandlerInterceptor接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("进入 preHandle 方法..." + request.getRequestURL().toString()); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("进入 postHandle 方法..." + request.getRequestURL().toString()); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("进入 afterCompletion 方法..." + request.getRequestURL().toString()); } }
|