Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Validation - BindingResult

I am trying to understand what BeanPropertyBindingResult does in the following code. Unfortunately, the javadoc is quite useless.

Please take a look at the following code:

BeanPropertyBindingResult errors = new BeanPropertyBindingResult(item, "item");
validator.validate(item, errors);

My questions are:

  1. As far as I can see, BeanPropertyBindingResult is basically some kind of a Map that can contain key/value pairs of (field name, error text). Is this correct, or is the truth more complicated?

  2. When I create a new BeanPropertyBindingResult, why do I need to provide it (as the constructor's first parameter) with the object I am going to validate? As far as I can see, in the second line above, validator.validate(item, errors); the validator gets the object anyway.. so why doing it twice?

  3. The javadoc says about the constructor's second parameter:

objectName - the name of the target object

yes, but why do I need that name? What am I supposed/able to do with it...?

like image 358
rapt Avatar asked Jan 25 '12 15:01

rapt


People also ask

What is the purpose of BindingResult in Spring MVC validation?

Interface BindingResult. General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building. Serves as result holder for a DataBinder , obtained via the DataBinder.

How do you validate a PATH variable?

Validating a PathVariable Just as with @RequestParam, we can use any annotation from the javax. validation. constraints package to validate a @PathVariable. The default message can be easily overwritten by setting the message parameter in the @Size annotation.


1 Answers

1) Yes, that is my understanding too, even if it is technically a list. -- The most importent part is List<ObjectError> errors defined in the superclass AbstractBindingResult.

2) Because it is demanded by the BindingResult Interface. -- I know this is not a good answer, but If this interfaces requires that method, then ther is no otherway to implement it BTW: I think I have seen some example before where the Autor used null for that field, but I am not 100% if it works correct, but most of the code seams to be able to handle the null value.

3) If you use that binding result for example in a jsp to show the error messages for different input fields, then this must match the model attribute name.

Assume you have a command object with a field name. And a JSP page where the input filed is associated to myCommand.name. Then you need the name myCommand as some kind of prefix for the binding errors. -- It is hard to explain, I hope you understand what I mean

like image 164
Ralph Avatar answered Oct 25 '22 01:10

Ralph