javahttprequestajax-request

How to redirect Ajax request to Login Page in Java


I want to redirect an Ajax request to login page at server side.

I can understand whether request is an Ajax request or not with

boolean isAjaxRequest = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

I know I can do it in JavaScript but there are a lot of places sending ajax request to server. So I have to do it in server-side. I tried;

httpResponse.redirect("...");

but it does not work.

How can I do that? Thanks.


Solution

  • Short answer: no.

    Long answer: It's possible, but not in the way you're thinking. If a redirect to a login page is required, presumably that means the user is currently not authenticated. Send back a 401 response - this will indicate to the client that a login is required.

    The trick now is to not handle the 401 in each call, but to handle it at some global point. For example, if you're using jQuery you can register a global error handler and check the status code - if it's a 401, then either redirect to the login page or otherwise accept authentication data.