Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Redirect after POST (even with validation errors)

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"; } 
like image 759
Taylor Leese Avatar asked Mar 30 '10 08:03

Taylor Leese


1 Answers

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"; } 
like image 116
Oscar Avatar answered Sep 21 '22 09:09

Oscar