java Spring - 将 BindingResult 添加到新创建的模型属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3052752/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring - adding BindingResult to newly created model attribute
提问by bezmax
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?
这东西确实有效,但是使用 MODEL_KEY_PREFIX 和属性名称创建密钥的那部分看起来很hackish,对我来说不是 Spring 风格。有没有办法让同样的东西更漂亮?
采纳答案by bezmax
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.
这意味着,如果我需要对用户未提交的一些常规数据进行一些自定义验证- 我需要添加一些自定义变量来保持该状态,而不是使用 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.
这回答了我对 BindingResult 的所有问题,因为我认为它必须用作任何类型错误的容器。
Again, thanks @Skaffman.
再次感谢@Skaffman。

