SpringMVC配置session過期攔截器,返回登錄頁面


spring-mvc.xml配置

<mvc:interceptors>
  <!-- session失效攔截器 -->
    <mvc:interceptor>   
    <!-- 匹配的是url路徑, 如果不配置或/**,將攔截所有的Controller --> 
      <mvc:mapping path="${frontPath}/**" />  
        <!-- 不需要攔截的地址 -->
        <mvc:exclude-mapping path="${frontPath}"/>
        <mvc:exclude-mapping path="${frontPath}/"/>
        <mvc:exclude-mapping path="${frontPath}/login"/> 
        <bean class="com.jeeplus.modules.sys.interceptor.SystemSessionInterceptor"></bean>   
    </mvc:interceptor> 
</mvc:interceptors>

攔截器類:

public class SystemSessionInterceptor implements HandlerInterceptor { 
    @Override
    public void postHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler, 
        ModelAndView modelAndView) throws Exception { 
    } 
      
    @Override
    public void afterCompletion(HttpServletRequest request, 
        HttpServletResponse response, Object handler, Exception ex) 
        throws Exception { 
    } 
      
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
        Object handler) throws Exception { 
        Principal principal = UserUtils.getPrincipal();
        if (principal == null) {  
            response.setContentType("text/html");  
            response.setCharacterEncoding("utf-8");  
            PrintWriter out = response.getWriter();    
            StringBuilder builder = new StringBuilder();    
            builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");    
            builder.append("alert(\"登錄已過期,請重新登錄!\");");    
            builder.append("parent.window.location.href='"+request.getContextPath()+"/f/login';");     
            builder.append("</script>");    
            out.print(builder.toString());    
            out.close();    
            return false;  
        }  
        return true;
    }
}

 


免責聲明!

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



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