Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - adding BindingResult to newly created model attribute

My task is - to create a model attribute by given request parameters, to validate it (in same method) and to give it whole to the View.

I was given this example code:

@Controller
class PromotionController {

    @RequestMapping("promo")
    public String showPromotion(@RequestParam String someRequestParam, Model model) {
        //Create the model attribute by request parameters
        Promotion promotion = Promotions.get(someRequestParam); 

        //Add the attribute to the model
        model.addAttribute("promotion", promotion); 

        if (!promotion.validate()) {
            BindingResult errors = new BeanPropertyBindingResult(promotion, "promotion");
            errors.reject("promotion.invalid");
            //TODO: This is the part I don't like
            model.put(BindingResult.MODEL_KEY_PREFIX + "promotion", errors);
        }
        return 
    }
}

This thing sure works, but that part with creating key with MODEL_KEY_PREFIX and attribute name looks very hackish and not a Spring style to me. Is there a way to make the same thing prettier?

like image 693
bezmax Avatar asked Jun 16 '10 11:06

bezmax


People also ask

How do you add attributes to a model?

To add new custom attributes to an entity, from the Edit Business Entity page, expand the Data Model section by clicking on it, then click the Insert button. The Add Attribute page appears where you will provide the properties.

What does BindingResult do in Spring?

[ BindingResult ] is Spring's object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

Can we map a request with model attribute?

Method level ModelAttribute annotation cannot be mapped directly with any request. Let's take a look at the following example for better understanding. We have 2 different methods in the above example.


1 Answers

Skaffman answered the question but disappeared, so I will answer it for him.

The binding validation thing is there to bind and validate parameters, not arbitrary business objects.

That means, that if I need to do some custom validation of some general data that was not submitted by the user - I need to add some custom variable to hold that status and not use BindingResult.

This answers all the questions I had with BindingResult, as I thought it had to be used as a container for any kind of errors.

Again, thanks @Skaffman.

like image 165
bezmax Avatar answered Sep 18 '22 09:09

bezmax