Spring - 将BindingResult添加到新创建的模型属性中 [英] Spring - adding BindingResult to newly created model attribute

查看:128
本文介绍了Spring - 将BindingResult添加到新创建的模型属性中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是 - 通过给定的请求参数创建模型属性,以验证它(以相同的方法)并将其整体赋予视图。



I给出了这个示例代码:

  @Controller 
class PromotionController {

@RequestMapping( promo)
public String showPromotion(@RequestParam String someRequestParam,Model model){
//按请求参数创建模型属性
Promotion promotion = Promotions.get(someRequestParam);

//将属性添加到模型
model.addAttribute(promotion,promotion);

if(!promotion.validate()){
BindingResult errors = new BeanPropertyBindingResult(promotion,promotion);
errors.reject(promotion.invalid);
// TODO:这是我不喜欢的部分
model.put(BindingResult.MODEL_KEY_PREFIX +promotion,错误);
}
返回
}
}

这事情确实有效,但是那个用MODEL_KEY_PREFIX和属性名称创建键的部分看起来非常h​​ackish而不是Spring风格。有没有办法让同样的东西更漂亮?

解决方案

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



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



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



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



<再次,谢谢@Skaffman。


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?

解决方案

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.

这篇关于Spring - 将BindingResult添加到新创建的模型属性中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆