Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a normal redirect from an ajax Spring MVC controller method

I have a Spring MVC controller method.

I would like for this method to:

  • return a JSon @ResponseBody (in ajax) if there are validation errors
  • perform a normal redirect to a given URL if there are no validation errors

Assuming I have a javabean object called myObject, I tried the following:

@RequestMapping(value = "/new", method = RequestMethod.POST)
@ResponseBody
public MyJavabeanObject myMethod(@RequestBody MyJavabeanObject myObject, BindingResult bindingResult, Model model,
        RedirectAttributes redirectAttributes, HttpServletResponse response) throws IOException {

    if (bindingResult.hasErrors()) {
        //adding error message to javabean
        return myObject;
    }

    response.sendRedirect("/success");
    return null;
}

Can anyone please let me know if what I am trying to achieve is at all possible?

like image 692
balteo Avatar asked Dec 09 '22 12:12

balteo


1 Answers

What you have will work as you describe it. Your method is annotated with @ResponseBody. Because of that a specific HandlerMethodReturnValueHandler, RequestResponseBodyMethodProcessor, will be dispatched to handle to returned object and write it to the response.

If instead you don't get errors, you send the redirect yourself directly and return null. When the returned value of your handler method is null, Spring's DispatcherServlet assumes that you handle generating the response yourself.

The only thing you have to worry about here is how your AJAX handler expects the response. In one case it'll get JSON, in the other it'll get whatever /success returns.

Note: if you expected the redirect to redirect the whole browser page from an AJAX request, this won't work. What you will need is to have a special case in your AJAX handler that will perform the browser page change itself by setting the window.location or something related.

like image 143
Sotirios Delimanolis Avatar answered Dec 11 '22 11:12

Sotirios Delimanolis