1

How to send the redirect from Spring controller if the return type is not String for the URL Handkler method.

@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public JsonResponse save(@RequestBody FormBean formBean) {  

    if(condition true)
      ? Save(formBean)
      : "redirect:/anotherUrl";

}

So JsonResponse which is a return type is actually a java class, how do i send redirect here ?

McQueen
  • 460
  • 2
  • 9
  • 20
  • You can return a ModelAndView, set the view to JsonView (or whatever it's appropriate name is) for JSON, return the "default" view otherwise (I think it's JspView or something like that...look at the View JavaDoc and see what implements it) – CodeChimp Mar 28 '14 at 19:25
  • Why do you want to redirect? It is not very logical to redirect when a `JsonResponse` is expected. – Bart Mar 28 '14 at 19:26
  • I am not using ModelAndView and that is the issue. for all the response I am using JSON response. – McQueen Mar 28 '14 at 19:27
  • Brat, I am implementing sychronizer token. So for every request, I check for the token, if it matches, the request proceed otherwise redirect the user to main page of the application. – McQueen Mar 28 '14 at 19:28
  • Have a look at [my answer here](http://stackoverflow.com/questions/15996779/cannot-handle-302-redirect-in-ajax-and-why/15996968#15996968). It's the proper way to handle your problem. – Bart Mar 28 '14 at 19:33

1 Answers1

1

You have to return a ResponseEntity from your controller method. It has an HttpStatus‘ and headers you can set, and a body that is your domain object. To redirect you would normally set the status toFOUND(302) and add aLocation` header with the URL for the client to redirect.

Dave Syer
  • 56,583
  • 10
  • 155
  • 143