Spring - Redirect after POST (even with validation errors)

Taylor Leese picture Taylor Leese · Mar 30, 2010 · Viewed 75.5k times · Source

I'm trying to figure out how to "preserve" the BindingResult so it can be used in a subsequent GET via the Spring <form:errors> tag. The reason I want to do this is because of Google App Engine's SSL limitations. I have a form which is displayed via HTTP and the post is to an HTTPS URL. If I only forward rather than redirect then the user would see the https://whatever.appspot.com/my/form URL. I'm trying to avoid this. Any ideas how to approach this?

Below is what I'd like to do, but I only see validation errors when I use return "create".

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public final String submit(
    @ModelAttribute("register") @Valid final Register register,
    final BindingResult binding) {

    if (binding.hasErrors()) {
        return "redirect:/register/create";
    }

    return "redirect:/register/success";
}

Answer

Oscar picture Oscar · Apr 6, 2012

Since Spring 3.1 you can use RedirectAttributes. Add the attributes that you want to have available before doing the redirect. Add both, the BindingResult and the object that you are using to validate, in this case Register.

For BindingResult you will use the name: "org.springframework.validation.BindingResult.[name of your ModelAttribute]".

For the object that you are using to validate you will use the name of ModelAttribute.

To use RedirectAttributes you have to add this in your config file. Among other things you are telling to Spring to use some newer classes:

<mvc:annotation-driven />

Now the errors will be displayed wherever you are redirecting

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public final String submit(@ModelAttribute("register") @Valid final Register register, final BindingResult binding, RedirectAttributes attr, HttpSession session) {

if (binding.hasErrors()) {
    attr.addFlashAttribute("org.springframework.validation.BindingResult.register", binding);
    attr.addFlashAttribute("register", register);
    return "redirect:/register/create";
}

return "redirect:/register/success";
}