Search code examples
javascriptjavaspringhttp-redirectmodelandview

ModelAndView does not redirect, but give correct response


I have the following function that makes a request:

function postIngredient(action, options) {
    var xhr = new XMLHttpRequest();
    xhr.open(options.method, action, true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xhr.setRequestHeader(options.security.header, options.security.token);

    // send the collected data as JSON
    xhr.send(JSON.stringify(options.params));

    xhr.onloadend = function () {
        // done
    };
}

The function triggers a method on the server that basically returns a ModelAndView object:

...   
ModelAndView mav = new ModelAndView("redirect:/recipies/edit?id=1");  
....  
return mav;  

After the post request is successfully done the following GET request is done: enter image description here

So in the 'Preview' tab of the request I have the correct page where it should redirect, but there is no redirection in the browser. The page remains the same where the postIngredient() function was initialy called. How then could the redirect be made?


Solution

  • You are making an ajax request via the XMLHttpRequest object from Javascript. This request is answered with a redirect and the XMLHttpRequest object follows the redirect, calls the edit and then the result of that (the complete page content for the edit page) is sent to your xhr.onloadend() method. The browser window itself is not involved in that and does not know that a redirect was sent internally.

    If you want to keep the post as an xhr request and do not switch to a standard form-post you might change your post processing method to just return a String:

    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ResponseBody
    public ResponseEntity<String> myPostProcessingIngredientsMethod(..put args here...) {
      ... do something ...
      return new ResponseEntity<>("/recipies/edit?id=1", HttpStatus.OK));
    }
    

    Then in your Javascript code where you do the xhr request, get the result string from the resultdata and redirect your browser with something like

    window.location.href = dataFromResult;
    

    The @ResponseBody annotation prevents Spring from interpreting the returned String as a view name and wrapping the String in a ResponseEntity gives you the possibility to return erroor codes if something goes wrong.