Spring - adding BindingResult to newly created model attribute
Asked Answered
M

1

19

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?

Mourant answered 16/6, 2010 at 11:18 Comment(4)
Which interface and which class are we in? And in which method?Demand
Added the class and method to the code.Mourant
I don't think there's going to be a nice way to do this. The binding validation thing is there to bind and validate parameters, not arbitrary business objects, so if you want to do that, it's going to be a bit messy.Implosive
Hm. So you propose that in case I could not find a Promotion with given parameters, I'd add some "String error" to the model containing the error? Never thought about this because I thought that BindingResult is a common container for all errors.Mourant
M
4

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.

Mourant answered 17/6, 2010 at 13:2 Comment(2)
No worries. By the way, if you want to post a comment addressed to a specific person, then prefix it with @username - that way the user gets notified.Implosive
I need to add some custom variable to hold that status and not use BindingResult. -- I don't agree. What you show in your question just works...Padilla

© 2022 - 2024 — McMap. All rights reserved.