拦截器

作者: 花无重日人未红 | 来源:发表于2020-02-19 21:06 被阅读0次
拦截器执行过程:
image.png
总结的几条拦截器规则:

1.preHandle 预处理:根据拦截器定义的顺序,正向执行(最先执行,在进入controller之前执行)使用场景:权限验证

2.postHandle 后处理:根据拦截器定义的顺序,逆向执行。需要所有的preHandle都返回true时才会调用(controller已经执行,modelAndView没有返回)应用场景:可以在此方法中设置全局的数据处理业务

3.afterCompletion 渲染后处理:根据拦截器定义的顺序,逆向执行。preHandle返回true就会调用(controller已经执行,modelAndView已经返回)应用场景:日志记录,性能检测

拦截器的应用

拦截器的应用:权限检查,日志记录,性能检测等;

在线用户拦截器示例
package com.supporter.prj.eip.online_user.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.supporter.prj.core.spring.SpringContextHolder;
import com.supporter.prj.eip.online_user.service.OnlineUserService;
import com.supporter.prj.eip_service.EIPService;
import com.supporter.prj.eip_service.online_user.entity.IOnlineUser;
import com.supporter.prj.eip_service.security.entity.UserProfile;
import com.supporter.util.CommonUtil;

/**
 * 拦截器
 *  controller 拦截器 
 */
public class OnlineUserInterceptor extends HandlerInterceptorAdapter {

    private OnlineUserService onlineUserService;
    private static final String FILTER = "service";
    private static final String CHECK = "service/eip/onlineuser/check";
    private static final String CHECK_SHOW_TIP = "service/eip/licence/checkShowTip";

    private static String userProfileKeyName = "sess_UserProfile";  
    
    private OnlineUserService getOnlineUserService() {
        if (onlineUserService == null) {
            onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
        }
        return onlineUserService;
    }

    private UserProfile getUserProfile(HttpSession session) {
        if (session == null) {
            EIPService.getLogService().error("session is null.");
            return null;
        }
        
        UserProfile user = (UserProfile) session.getAttribute(userProfileKeyName);
        return user;
    }
    
    /**   
     * 在业务处理器处理请求之前被调用   
     * 如果返回false   
     *    从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链   
     * 如果返回true   
     *    执行下一个拦截器,直到所有的拦截器都执行完毕   
     *    再执行被拦截的Controller   
     *    然后进入拦截器链,   
     *    从最后一个拦截器往回执行所有的postHandle()   
     *    接着再从最后一个拦截器往回执行所有的afterCompletion()   
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = CommonUtil.trim(request.getRequestURI());
        if (requestUrl.indexOf(CHECK) >= 0 || requestUrl.indexOf(CHECK_SHOW_TIP) >= 0) {
            return true;
        }
        
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                String sessionId = session.getId();
                IOnlineUser onlineUser = getOnlineUserService().getOnlineUser(sessionId);
                if (onlineUser == null) {
                    //找不到对应的在线用户
                    UserProfile userProfile = getUserProfile(session);
                    if (userProfile != null) {
                        userProfile.setInitialized(false);
                    }
                } else {
                    if (!onlineUser.isActive()) {
                        //在线用户是不活跃的
                        UserProfile userProfile = getUserProfile(session);
                        if (userProfile != null) {
                            userProfile.setInitialized(false);
                        }
                    }
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    /**
    * 在Controller方法后进行拦截
    */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        String requestUrl = CommonUtil.trim(request.getRequestURI());
        if (requestUrl.indexOf(CHECK) >= 0 || requestUrl.indexOf(CHECK_SHOW_TIP) >= 0) {
            return;
        } 
        if (requestUrl.indexOf(FILTER) >= 0) {
            //只有url中带有“service"的才做刷新在线用户的操作
            try {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    String sessionId = session.getId();
                    getOnlineUserService().refresh(sessionId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
拦截器配置

在spring_mvc.xml文件中配置

<!-- 拦截器 -->
    <mvc:interceptors>
       <mvc:interceptor>
        <mvc:mapping path="/**" />
        <mvc:exclude-mapping path="/service/eip/logon/in"/>
        <bean class="com.supporter.prj.eip.online_user.interceptor.OnlineUserInterceptor" />
       </mvc:interceptor>
       
       <mvc:interceptor>
        <mvc:mapping path="/**" />
        <mvc:exclude-mapping path="/service/out/test/getAuthorization"/>
        <bean class="com.supporter.prj.trans_power.AuthInterceptor" />
       </mvc:interceptor>
    </mvc:interceptors>

相关文章

网友评论

      本文标题:拦截器

      本文链接:https://www.haomeiwen.com/subject/cewgfhtx.html