Search code examples
javascriptajaxservletsextjsextjs3

Response sendRedirect not working with AJAX request


I have a web application with java and EXT JS(3.4). For all servlets, this is what I have in my doGet method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        response.sendRedirect("ErrorPage.jsp");
    } catch (Throwable t) {
        //do some logging
    }
}

I simulate a GET request, with EXT JS using:

Ext.Ajax.request({
    method : 'GET',
    url : 'web'//web is the servlet name
});

The page does not redirect. This is the output from tamperData plugin of firefox:

Tamper Data Output

If you are unable to see image, it says that the AJAX Get request responded with status 302:meaning redirect, and there was a request for ErrorPage.jsp which returned a status code of 200:meaning that the request completed successfully.
If i alert the response in the callback of the ajax request, it alerts the contents of the ErrorPage.jsp. I have a large number of such AJAX requests. Is there any reason why the redirect is not working.

I added the following code as well. But i always get status as 200. When though i can see in firebug that for a get request first request gave status 302 and the second one for Error Page gave 200.

Ext.Ajax.on('requestcomplete', function(conn, response, options) {
                alert('successful'+response.status)
            });
            Ext.Ajax.on('requestexception', function(conn, response, options) {
                alert('failed'+response.status)
            });

Details:

OS : Windows 7
Server : Apache Tomcat 7.0.42
Servlet Api: Using servlet-api-3.0.jar


Solution

  • Based on @AnthonyGrist's post, this is the solution i came up with for EXT JS.
    In the controller I changed doGet to :

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
           response.setStatus(403);
        } catch (Throwable t) {
            //do something
        }
    }
    

    A status code of 403 is recognised in EXT JS as a failure.So in the jsp page :

    Ext.Ajax.on('requestexception', function(conn, response, options) {
               if(response.status=403){
                    window.location.assign("ErrorPage.jsp");
     }
    });