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;
    }
}

 

posted @ 2017-12-15 10:41  如果屈原会编程  阅读(5321)  评论(0编辑  收藏  举报