Spring MVC 攔截器系列-會話超時攔截器


工作已經七個年頭,一直都在為別人或者為公司服務,近段時間突然想把自己這幾年積累的東西寫出來,這樣一方面對於自己的文筆是一種鍛煉,另一方面也可以加強自己的記憶,同時還能給未遇到相同的問題的朋友提供幫助。

好了,費話就不多說了,進入今天的主題——Spring MVC攔截器-會話超時攔截器

所謂攔截器,從字面意思不難理解,作用就是對於行為或者動作進行攔截。

SpringMVC 攔截器概述

    SpringMVC 中的Interceptor 攔截請求是通過HandlerInterceptor 來實現的。在SpringMVC 中定義一個Interceptor 非常簡單,主要有兩種方式,第一種方式是要定義的Interceptor類要實現了Spring 的HandlerInterceptor 接口,或者是這個類繼承實現了HandlerInterceptor 接口的類,比如Spring 已經提供的實現了HandlerInterceptor 接口的抽象類HandlerInterceptorAdapter ;第二種方式是實現Spring的WebRequestInterceptor接口,或者是繼承實現了WebRequestInterceptor的類。

1. 要使用攔截器,第一步就必須要引入SpringMVC相關的Jar文件,同時還需要引入aopalliance.jar文件;

2. 定義攔截器類:SessionTimeoutInterceptor

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.jack.lanqiubus.common.constant.SiteConstant;
import com.jack.lanqiubus.model.admin.SysUserModel;

/**
 * @description: 處理session超時的攔截器 會話控制攔截器
 * 
 */
public class SessionTimeoutInterceptor  implements HandlerInterceptor{
    
    public String[] allowUrls;//還沒發現可以直接配置不攔截的資源,所以在代碼里面來排除

    @Autowired
    private ResourceBundleMessageSource _res;
    
    public void setAllowUrls(String[] allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");  
        if(null != allowUrls && allowUrls.length>=1)
            for(String url : allowUrls) {  
                if(requestUrl.contains(url)) {
                    return true;  
                }  
            }
        
        SysUserModel user = (SysUserModel) request.getSession().getAttribute(SiteConstant.AUTHENTICATION_KEY);
        if(user != null) {  
            return true;  //返回true,則這個方面調用后會接着調用postHandle(),  afterCompletion()
        }else{
            /**
             * 如果無法忍受每次都拋出異常時,可以使用此方法進行頁面跳轉
             */
//            PrintWriter out = response.getWriter();  
//            out.println("{\"statusCode\":\"301\", \"message\":\""+this.getMessage(request,"msg.session.invalid")+"\"}");
//            String page = request.getContextPath() + "/views/admin/ajaxDone.jsp?statusCode=301&message="+this.getMessage(request,"msg.session.invalid");
//            response.sendRedirect(page);
//            return false;
            // 未登錄  跳轉到登錄頁面
            throw new SessionTimeoutException();//返回到配置文件中定義的路徑
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
    }
    
    protected String getMessage(HttpServletRequest request, String code, Object... args) {
        //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        Locale locale = localeResolver.resolveLocale(request);

        return _res.getMessage(code, args, locale);
    }

}

3. 會話超時異常捕獲類:SessionTimeoutException此類可以直接新建一個類並繼承自Exception就OK了,不需要做其他方法的聲明,如果有需要做的特殊處理可以自行添加。

public class SessionTimeoutException extends Exception {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

4. 上面2,3兩部已經把攔截器進行了定義,如果要使用攔截器進行正常工作的話,還需要進行適合的配置,配置如下[攔截器代碼需要添加在Spring的配置文件中]:

<!-- 進行登錄攔截  [-->
    <!-- 攔截器配置 -->
    <mvc:interceptors>
      <!-- session超時 -->
      <mvc:interceptor>
        <mvc:mapping path="/*/*/*"/><!-- 此處將攔截所有包含三層路徑的所有URL請求,可以根據個人使用的實際情況進行修改 -->
        <bean class="com.jack.lanqiubus.admin.SessionTimeoutInterceptor">
          <property name="allowUrls">
            <list>
              <!-- 如果請求中包含以下路徑,則不進行攔截 -->
              <value>/login</value>
              <value>/loginDialog</value>
              <value>/logout</value>
              <value>/js</value>
              <value>/css</value>
              <value>/image</value>
              <value>/images</value>
            </list>
          </property>
        </bean>
      </mvc:interceptor>
    </mvc:interceptors>
    
    <!-- 自定義異常處理,SimpleMappingExceptionResolver這個類可以是個空類,但是要寫,方便在java代碼里面使用 -->
      <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
        <props>
          <prop key="com.jack.lanqiubus.admin.SessionTimeoutException">redirect:/admin/transfer</prop>
        </props>
      </property>
    </bean>
    <!--] 進行登錄攔截  -->

其中異常捕獲后的 redirect:/admin/transfer  此處為Spring MVC要進行跳轉登錄頁面地址,可自行進行配置處理。

個人網站地址:http://www.52cfml.com/post/Springmvc_SessionTimeoutInterceptor.html

后續會推出:

Spring MVC 攔截器系列-權限控制攔截器

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM