1.与过滤器filter的区别
2.springMVC中拦截器的必须实现的三个方法:
3. 拦截器类的编写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package com.imooc.core; import com.imooc.bean.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { //在业务处理器被调用前的方法,若是返回false则不会继续进入业务处理器 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { User user = (User)request.getSession().getAttribute( "session_user" ); if (user== null ) { response.sendRedirect(request.getContextPath()+ "/login" ); return false ; //会终止所有的请求 } return true ; } //在业务处理器被调用后,dispatcher响应客户端前的方法,一般用于生成日志文件时调用 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } //dispatcher响应客户端后的方法,一般用于资源的清理 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } |
4.在spring的配置文件中注册拦截器:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!-- 拦截器的注册 --> <mvc:interceptors> <mvc:interceptor> <!--**表示往后的所有子目录也包括进来--> <mvc:mapping path= "/user/**" ></mvc:mapping> <!--exclude-mapping在所有拦截中进行排除,一般在通配符会有意义。--> <!--即以下的方法不会被拦截--> <mvc:exclude-mapping path= "/user/updatepwd" ></mvc:exclude-mapping> <mvc:exclude-mapping path= "/user/updatebackground/*" ></mvc:exclude-mapping> <!--填写之前配置好的拦截器--> <bean class = "com.imooc.core.LoginInterceptor" ></bean> </mvc:interceptor> </mvc:interceptors> |
注意:要是有多个拦截器执行顺序以spring的配置文件中的注册拦截器顺序执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!-- 拦截器的注册 --> < mvc:interceptors > <!--先注册先执行--> < mvc:interceptor > < mvc:mapping path = "/user/**" /> < bean class = "com.imooc.core.LogInterceptor" ></ bean > </ mvc:interceptor > < mvc:interceptor > < mvc:mapping path = "/user/**" ></ mvc:mapping > <!--exclude-mapping在所有拦截中进行排除,一般在通配符会有意义。--> < mvc:exclude-mapping path = "/user/updatepwd" ></ mvc:exclude-mapping > < mvc:exclude-mapping path = "/user/updatebackground/*" ></ mvc:exclude-mapping > < bean class = "com.imooc.core.LoginInterceptor" ></ bean > </ mvc:interceptor > </ mvc:interceptors > |
其次拦截器里的方法顺序:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/188490/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)