Question

I am new to Spring and need a little guidance. I have through the Spring tutorials, but cannot find what I am looking for. I want to know what is the best way to handle this scenario:

  1. User goes to index page and it presented with a form.
  2. User fills out forms and submits to a new URL (Passes client side validation)
  3. During Spring validation of the form object, it detect errors
  4. Redirect the user back to the index page with the affected fields highlighted

I am assuming this is the correct flow for this situation. if not, please tell me otherwise. If this is the correct flow, how do I pass the binding/validation errors to the template?

Was it helpful?

Solution

In this situation follow Post/Redirect/Get pattern flow. When server side validation fails (result.hasErrors()) do not redirect but display index page again. Spring handles passing errors to template. To display errors use function of your template engine that supports Spring MVC (for example display all errors in JSP - <form:errors path="*" element="div" />).

@Controller
public class MyController {

    @RequestMapping(value="/index.html", method=RequestMethod.GET)
    public String display(@ModelAttribute MyForm myForm){
        return "index";
    }

    @RequestMapping(value="/process.do", method=RequestMethod.POST)
    public String processForm(@ModelAttribute @Validated MyForm myForm, 
                          BindingResult result) {

        if(result.hasErrors()){
            return display(myForm);
        }

        return "redirect:/processed.html";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top