Solution to invalid redirection of $. ajax request interceptor

Using redirect page in interceptor filter under ajax asynchronous request is invalid

I use the springboot framework here. I use the interceptor to intercept the request. When the session timeout, I directly jump to the login.html page.

Background code:

@Override
    public void addInterceptors(InterceptorRegistry registry)
    {
    //Load custom interceptor (login request and exit request release)
        registry.addInterceptor(new DemoIntercept()).addPathPatterns("/**").excludePathPatterns("/loginController","/logout");
    }


/**
*custom interceptor 
**/
public class DemoIntercept implements HandlerInterceptor
{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
            throws Exception
    {
        logger.info("afterCompletion:{}", request.getRequestURI());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception
    {
        logger.info("postHandle:{}", request.getRequestURI());
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception
    {
        //Get session
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        //If the user is null, it will be redirected to the login page, otherwise it will be released
        if(null == username)
        {
            //Redirect to login.html
             redirect(request, response); 
             return false;
        }
        return true;
    }


      //How to deal with the problem that the request is the ajax request redirection
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //Get the path of the current request
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        //If "XMLHttpRequest" is returned by request.getHeader("X-Requested-With"), it means that it is an ajax request, which needs special processing or direct redirection
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //Tell ajax I'm redirecting
            response.setHeader("REDIRECT", "REDIRECT");
            //Tell ajax where to redirect
            response.setHeader("CONTENTPATH", basePath+"/login.html");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }else{
            response.sendRedirect(basePath + "/login.html");
        }
    }
}

Foreground code

//Here we add a complete function to all ajax requests
$.ajaxSetup({
            complete : function(xhr, status) {
                //Interceptor realizes timeout jump to login page
                // Get response header through xhr
                var REDIRECT = xhr.getResponseHeader("REDIRECT");
                //If the response header contains REDIRECT, the interceptor returns it
                if (REDIRECT == "REDIRECT")
                {
                    var win = window;
                    while (win != win.top)
                    {
                        win = win.top;
                    }
                    //Jump to login.html again 
                    win.location.href = xhr.getResponseHeader("CONTEXTPATH");
                }
            }
        });

The principle of implementation here is that the background marks the ajax request header with a REDIRECT, and the foreground judges whether the response header needs to be redirected according to the REDIRECT after receiving the response. If so, it is OK to obtain the REDIRECT address

Tags: Session SpringBoot

Posted on Sun, 03 May 2020 02:57:54 -0400 by computerzworld