我的任务是 - 通过给定的请求参数创建模型属性,以验证它(以相同的方法)并将其整体赋予视图。
我得到了这个示例代码:
@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和属性名称创建键的部分看起来非常hackish而不是Spring风格。有没有办法让同样的东西漂亮?
答案 0 :(得分:3)
Skaffman回答了这个问题但却消失了,所以我会为他回答。
绑定验证是绑定和验证参数,而不是任意业务对象。
这意味着,如果我需要对某些未由用户提交的常规数据进行自定义验证 - 我需要添加一些自定义变量来保存该状态而不使用BindingResult。
这回答了我对BindingResult的所有问题,因为我认为它必须被用作任何类型错误的容器。
再次感谢@Skaffman。