开发者

Trying to understand the workflow for basic form validation using Spring

New to Spring here, and after reading the reference docs the workflow to validate a simple web form isn't popping out at me.

Could someone give me a beginners overview of how we go about form validation in Spring 3.0.3 (I'm using a mix of annotations and xml config in a webapp that I'm migrating now). Starting from the Controller, what happens?

For example: so far I think I understand that I should "bind" the form data to an object of my creation (say MyPerson for example), then create a Validation object that accepts MyPerson and uses Vali开发者_StackOverflow中文版dationUtils to perform the validation.

But that's all very fuzzy in my head (especially the "binding" concept) and a step by step review of the workflow from someone who's been through it before would help me be confident that I'm not missing or mis-interpreting any steps.


The method you are mentioning for validating forms is one of a few options you have available.

As well as the method you have suggested you may also want to investigate using JSR-303 annotations with an appropriate implementation (for example Hibernate Validator). There are a lot of example of how to accomplish this.

For the spring validation method your basic steps are:

  • Create an class to act as a binding object, pass an instance of this to the view in your controller
  • Bind the object to the fields in your view using the form taglib
  • In the controller method which handles the form submission, use the @ModelAttribute annotation to bind the form data to your binding object
  • Use your custom validator object (probably @Autowired to your controller) to perform validation

Heres a simple example controller:

@Controller
public class PersonController {

@Autowired
private PersonValidator personValidator;

@RequestMapping(value="person/form", method = RequestMethod.GET)
public ModelAndView form() {
    // Instance of binding object
    Person person = new Person();

    // Create ModelAndView which displays personForm view
    ModelAndView mav = new ModelAndView("person/form");
    // Put our binding object in the model
    mav.getModel().put("person", person);

    return mav;
}

@RequestMapping(value="person/form", method = RequestMethod.POST)
public String save(@ModelAttribute Person person, BindingResult errors, Model model) {
    // Call our custom validator and put errors into BindingResult
    personValidator.validate(person, errors);

    // If we have validation errors
    if (errors.hasErrors()) {
        // Show form with errors
        return "person/form";
    }

    // Otherwise show some success page
    return "person/success";
 }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜