首页 > 编程语言 > 详细

springMVC的拦截器配置

时间:2020-06-05 00:43:55      阅读:45      评论:0      收藏:0      [点我收藏+]

1.与过滤器filter的区别

技术分享图片

 

 

 2.springMVC中拦截器的必须实现的三个方法:

技术分享图片

 

 

 技术分享图片

 

 

 3. 拦截器类的编写:

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的配置文件中注册拦截器:

    <!-- 拦截器的注册 -->
    <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的配置文件中的注册拦截器顺序执行:

    <!-- 拦截器的注册 -->
    <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>

其次拦截器里的方法顺序:

技术分享图片

 

springMVC的拦截器配置

原文:https://www.cnblogs.com/shouyaya/p/13047129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!