I have a Spring MVC controller method.
I would like for this method to:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With