Java 2種方法實現簡單的session超時登出


  

 1、使用攔截器 

 

       用戶每次和后台交互,如果用戶長時間未操作,則需要檢測用戶的登錄狀態,這樣的場景已經是再正常不過了。

  傳統的做法可以在每個controller里先判斷user的狀態,然后再執行業務操作,但這樣比較代碼不夠精簡,優雅。

  可以使用最簡單的攔截器,如:

  

public class LoginInterceptor extends HandlerInterceptorAdapter {

    private List<String> IGNORE_URI;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     

        HttpSession session = request.getSession();
        if(session != null && session.getAttribute("login_status") != null){ 
            return true;
        }else{
            response.sendRedirect("/user/login?timeout=true");
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
  
  
  public List<String> getIGNORE_URI() {
return IGNORE_URI;
}

  public void setIGNORE_URI(List<String> IGNORE_URI) {
this.IGNORE_URI = IGNORE_URI;
}

   }

  只要我們在登錄的時候給session設個值,每次進入方法的時候,都先會執行攔截器中的preHandle()方法,如果session已經失效則重定向到登錄頁面。

 

     spring-mvc.xml的配置:

 

<mvc:interceptors>
        <!-- 登陸攔截器,負責攔截未登錄的操作 -->
        <mvc:interceptor>
            <!-- 需要攔截的地址 -->
            <mvc:mapping path="/**"/>
            <!-- 需要排除攔截的地址 -->
            <mvc:exclude-mapping path="/static/**"/>
            <bean id="loginInterceptor" class="com.amayadream.webchat.interceptor.LoginInterceptor">
                <property name="IGNORE_URI">
                    <list>
                        <value>/user/login</value>
                        <value>/user/logout</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

 

   2、使用Shiro的session會話管理

      具體的使用可以看我的另一篇博客:https://www.cnblogs.com/qsymg/p/9836122.html

  

 

  


免責聲明!

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



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