Spring-将BindingResult添加到新创建的模型属性


问题内容

我的任务是-通过给定的请求参数创建模型属性,对其进行验证(以相同的方法)并将其整体提供给View。

我得到了以下示例代码:

@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 
    }
}

这件事确实可行,但是对我来说,用MODEL_KEY_PREFIX和属性名创建密钥的那一部分看起来很黑,不是Spring风格。有没有办法使同一件事更漂亮?


问题答案:

Skaffman回答了问题,但消失了,所以我会为他回答。

绑定验证是用来绑定和验证参数的,而不是任意业务对象。

这意味着,如果我需要对 用户未提交 的一些常规数据进行一些自定义验证,则需要添加一些自定义变量来保持该状态,而不使用BindingResult。

这回答了我对BindingResult的所有疑问,因为我认为必须将其用作任何类型的错误的容器。

再次感谢@Skaffman。