user3334871
user3334871

Reputation: 1361

Redirect to a page after an Ajax call where URL is determined in Spring controller

On my JSP page, I am making an Ajax post to my Spring controller. I use the data I am posting to determine where I should make a redirect call to. So my code would look like:

@RequestMapping(value="/postFromJSP" method={RequestMethod.POST})
public void sendRedirect(HttpServletRequest request,
                         HttpServletResponse response,
                         @RequestBody MyAjaxData data) {

    RestResponse restResponse = determineRedirect(data);

    if (restResponse.getStatusCode()==302) {
       //redirect to URL from response
       Cookie cookie = generateCookie(restResponse.getJson());
       url = restResponse.getJson.getURL();
       response.addCookie(cookie);
       response.sendRedirect(url);
     }
  }

However, from my JSP page, when I examine the network traffic, I see a 307 response to my redirect request to the specified URL, and the view doesn't change from my JSP.

What am I doing wrong? Do I need to add in a success function in my Ajax to make the redirect?

Upvotes: 2

Views: 126

Answers (1)

Supun Dharmarathne
Supun Dharmarathne

Reputation: 1148

Change Spring Controller like this.

 @RequestMapping(value="/postFromJSP" method={RequestMethod.POST})
 public RestResponse sendRedirect(HttpServletRequest request,
                     HttpServletResponse response,
                     @RequestBody MyAjaxData data) {

RestResponse restResponse = determineRedirect(data);

return restResponse ;

}

Handle the response inside the callback function in .js

Upvotes: 2

Related Questions