Session过期后自动跳转到登陆页

需求描述:实现30分钟无操作自动退出的功能

知识关联如下:

1.关于session的问题

2.Session过期后自动跳转到登陆页

3.Filter过滤器例外URL设置

配置步骤如下:

1、web.xml中添加过滤器配置


        sessionFilter
        com.orchestrall.web.helper.session.SessionFilter


        sessionFilter
        /actions/*

2、新建SessionFilter类,实现Filter接口

public class SessionFilterimplements Filter {
    public void destroy() {
        // TODO Auto-generated method stub
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        // 登陆url
        String loginUrl = httpRequest.getContextPath() + "/admin/login.jsp";
        String url = httpRequest.getRequestURI();
        String path = url.substring(url.lastIndexOf("/"));
        // 超时处理,ajax请求超时设置超时状态,页面请求超时则返回提示并重定向
        if (path.indexOf(".action") != -1
                && session.getAttribute("LOGIN_SUCCESS") == null) {
            // 判断是否为ajax请求
            if (httpRequest.getHeader("x-requested-with") != null
                    && httpRequest.getHeader("x-requested-with")
                            .equalsIgnoreCase("XMLHttpRequest")) {
                httpResponse.addHeader("sessionstatus", "timeOut");
                httpResponse.addHeader("loginPath", loginUrl);
                chain.doFilter(request, response);// 不可少,否则请求会出错
            } else {
                String str = "";
                response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
                try {
                    PrintWriter writer = response.getWriter();
                    writer.write(str);
                    writer.flush();
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            chain.doFilter(request, response);
        }
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
}
3.客户端JS,用于ajax请求session超时
对于jquery

对于extjs的ajax请求
Ext.Ajax.on('requestcomplete',checkUserSessionStatus, this);
    function checkUserSessionStatus(conn,response,options){
        if(response.getResponseHeader("sessionstatus") == 'timeout'){
            if(response.getResponseHeader("loginPath")){
                alert("会话过期,请重新登陆!");
                window.top.location.href = response.getResponseHeader("loginPath");
            }else{
                alert("请求超时请重新登陆 !");
            }
        }
    }
如果使某个ajax请求不受全局方法的影响,那么可以在使用$.ajax()方法时,将参数中的global设置为false,jquery代码如下:
$.ajax({
    url:"test.html",
    global:false//不触发全局ajax事件
})

你可能感兴趣的:(后端开发)