Spring annotations @ModelAttribute and @Valid

后端 未结 2 702
谎友^
谎友^ 2020-12-31 11:02

What are the advantages of using @ModelAttribute and @Valid?

Which are the differences?

Is it possible to use them together?

2条回答
  •  猫巷女王i
    2020-12-31 11:14

    please check the below part fro spring reference documentation:

    In addition to data binding you can also invoke validation using your own custom validator passing the same BindingResult that was used to record data binding errors. That allows for data binding and validation errors to be accumulated in one place and subsequently reported back to the user:

    @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
        return "petForm";
        }
    
        // ...
    }
    

    Or you can have validation invoked automatically by adding the JSR-303 @Valid annotation:

    @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
    public String processSubmit(@Valid @ModelAttribute("pet") Pet pet, BindingResult result)             {
        if (result.hasErrors()) {
            return "petForm";
        }
    
        // ...
    
    }
    

提交回复
热议问题