Home > Net >  Java Spring intercept from which URL is calling another URL
Java Spring intercept from which URL is calling another URL

Time:11-04

I have the following requirement:

During the checkout process, once the user is located in the checkout page, if the user tries to "escape" from this checkout URL (ex: going to homepage or my account section or any other external page) it must be redirected to the checkout URL again. Is there any way to achieve this using Spring interceptors?

CodePudding user response:

You should be able to access current page from referrer HTTP Header, so interceptor logic will look like this:

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final var referrerHeader = request.getHeader("referrer");
        if(isCheckoutUrl(referrerHeader) // user navigates from checkout 
              && !isCheckoutUrl(request.getRequestURI()) // to other page
        ){
            // send him back
            response.sendRedirect(getCheckoutUrl());
            return false;
        }
        return true;
    }
  • Related