Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring annotations @ModelAttribute and @Valid

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

Which are the differences?

Is it possible to use them together?

like image 685
vdenotaris Avatar asked Mar 26 '14 10:03

vdenotaris


People also ask

What is @valid annotation in Spring?

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations.

What is @ModelAttribute annotation in Spring?

@ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view. In this tutorial, we'll demonstrate the usability and functionality of this annotation through a common concept, a form submitted from a company's employee.

What is @valid annotation for?

The @Valid annotation is a key feature of Bean Validation, as it allows to validate object graphs with a single call to the validator. To make use of it all fields that should be recursively checked should be annotated with @Valid .

What is @valid in Spring boot?

When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument. When the target argument fails to pass the validation, Spring Boot throws a MethodArgumentNotValidException exception.


1 Answers

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";
    }

    // ...

}
like image 56
Bassem Reda Zohdy Avatar answered Sep 21 '22 18:09

Bassem Reda Zohdy