Announcement Announcement Module
No announcement yet.
RedirectAttributes and BindingResult Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • RedirectAttributes and BindingResult

    I was playing with the new RedirectAttribute in spring and wanted to be able to do a post redirect get pattern while passing the binding results back to the GET method. If I key my BindingResults in the POST RedirectAttributes as BindingResult.MODEL_KEY_PREFIX + "user", then in the GET method the binding result is cleared because I'm assuming my modelMap entry gets overwritten by a empty BindingResult for the new method.

    I've come up with the solution below, which keys my binding results as "errors" in the POST and then in the GET method I pull it out and stick it in the modelMap under BindingResult.MODEL_KEY_PREFIX+"user". Is there a better way to achieve this? Thanks for any help.

    @RequestMapping(value = "users")
    public class UserController {
    	@RequestMapping(method = RequestMethod.GET, value = "post")
    	public String postGet(@ModelAttribute("user") User user, ModelMap modelMap) {
    		 * When I try to send the redirectAttribte with
    		 * BindingResult.MODEL_KEY_PREFIX+"user" as the key, my binding gets
    		 * erased. This is only way I can figure out how to do this, and will
    		 * change it if I ever see a better way.
    		modelMap.put(BindingResult.MODEL_KEY_PREFIX + "user",
    		return "users/post";
    	@RequestMapping(method = RequestMethod.POST)
    	public String testPost(@Valid @ModelAttribute("user") User user,
    			BindingResult errors, RedirectAttributes redirectAttributes) {
    		if (errors.hasErrors()) {
    			redirectAttributes.addFlashAttribute("user", user);
    			redirectAttributes.addFlashAttribute("errors", errors);
    			return "redirect:users/post";
    		redirectAttributes.addAttribute("userId", user.getUserId());
    		return "redirect:users/{userId}";