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

我的任务是 – 通过给定的请求参数创建模型属性,以validation它(以相同的方法)并将其整体提供给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和属性名创建键的部分看起来非常h​​ackish而不是Spring风格。 有没有办法让同样的东西漂亮?

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

绑定validation的事情是绑定和validation参数,而不是任意业务对象。

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

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

再次感谢@Skaffman。