欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

过滤器(当前登录人的信息(session过期时)进行重新登录) 过滤器session过期

程序员文章站 2022-04-21 22:19:31
...
第一步:书写过滤器类,过滤器必须继承org.springframework.web.servlet.handler.HandlerInterceptorAdapter并重写preHandle方法。

/**
* 检测是否已经登录
* <p>Title:SecurityInterceptor </p>
* <p>Description: </p>
* @author zhanghaodong
* @date 2015年11月27日 上午11:18:56
*/
public class SecurityInterceptor extends HandlerInterceptorAdapter {

        @Override 
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
            if((request.getContextPath().replace("/", "")).equals((request.getRequestURI().replace("/", "")))){
                return true;
            }
            HttpSession session = request.getSession(true); 
            // 从session 里面获取用户名的信息 
            Object obj =session.getAttribute(WebCnts.SESSION_KEY_LOGINUSER);
            // 判断如果没有取到用户信息,就跳转到登陆页面,提示用户进行登陆 
            if (obj == null || "".equals(obj.toString())) { 
                  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()+"/login';");    
                    builder.append("</script>");   
                    out.print(builder.toString());   
                    out.close();   
                    return false; 
            } 
            return true; 
        } 

        @Override 
        public void postHandle(HttpServletRequest req, HttpServletResponse res, Object arg2, ModelAndView arg3) throws Exception { 
        } 

        @Override 
        public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object arg2, Exception arg3) throws Exception { 
        } 

}



第二步:在spring-mvc.xml文件中添加下面代码(过滤的路径)

    <mvc:interceptors>
        <mvc:interceptor>
           <!--过滤所有的路径  -->
            <mvc:mapping path="/**"/>
     <!--去掉不需要进行过滤的路径,如:静态的路径  -->
            <mvc:exclude-mapping path="/login"/> 
            <mvc:exclude-mapping path="/plugins/**"/> 
            <mvc:exclude-mapping path="/public/**"/> 
            <mvc:exclude-mapping path="/upload/**"/> 
            <mvc:exclude-mapping path="/getCaptha"/> 
            <mvc:exclude-mapping path="/demo/*.json"/> 
            <bean class="com.hiersun.ecommerce.security.SecurityInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>