Ajax access background session timeout processing

 

In web development, there is usually session timeout processing, which is easier to handle for ordinary http requests, but may require special processing for ajax asynchronous requests

 

/* server side: interceptor or filter processing: */
 
// Processing of asynchronous request session timeout
if (request.getHeader("x-requested-with") != null &&
    request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
    PrintWriter wirter =  response.getWriter();
    wirter.write("timeout");
    wirter.flush();
} else {              
    // Processing of ordinary http request session timeout
    return Action.LOGIN;
}

 

/* Browser side: JQuery adds global AJAX default options: complete callback function: */
 
$.ajaxSetup({
    global: false,
    type: "POST",
    complete: function (XMLHttpRequest, textStatus) {
        var data = XMLHttpRequest.responseText;
        if (data == "timeout") {
            if( window.top != window.self ){
                window.top.location = "${pageContext.request.contextPath}";
            }
        }
    }
});

 Another note:

The order of execution of each event in jquery is as follows:
    ajaxStart (global event)
    beforeSend
    ajaxSend (global event)
    success
    ajaxSuccess (global event)
    error
    ajaxError (global event)
    complete
    ajaxComplete (global event)
    ajaxStop (global event)

 Unified encapsulation of AJAX requests, monitoring response headers, if sessionStatus is timeout

Then just use JS to jump to the login window.location

 

function checkSessionTimeout(response){
    if(response.getResponseHeader){
        var sessionStatus = response.getResponseHeader("sessionstatus");
        if (sessionStatus == 'timeout') {
            var redirect = response.getResponseHeader("Location");
            window.location = redirect;
            return;
        }
    }
}

 Customize an interceptor and throw it out at timeout

   response.setHeader("Location",request.getContextPath()+timeoutUrl);
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Login timed out or invalid!");
    response.setHeader("sessionstatus", "timeout");

 You can judge whether the request is ajax according to the request header. If it is ordinary, you don't need to jump directly to login. If it is AJAX, it will throw a status code. If you don't want to customize the interceptor, you can directly monitor the status code of the response.

 

http://www.cnblogs.com/zolz/articles/4883698.html

 

refer to:

http://www.anyrt.com/blog/list/ajaxsession.html

http://daichangfu.iteye.com/blog/1705097

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326524292&siteId=291194637