【发布时间】:2011-03-04 10:10:43
【问题描述】:
我的任务是 - 通过给定的请求参数创建模型属性,验证它(以相同的方法)并将其完整地提供给视图。
我得到了这个示例代码:
@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 风格。有没有办法让同样的东西更漂亮?
【问题讨论】:
-
我们在哪个接口和哪个类?用什么方法?
-
将类和方法添加到代码中。
-
我不认为会有很好的方法来做到这一点。绑定验证是用来绑定和验证参数的,而不是任意的业务对象,所以如果你想这样做,它会有点乱。
-
嗯。因此,您建议如果我找不到具有给定参数的促销活动,我会在包含错误的模型中添加一些“字符串错误”?从来没有想过这个,因为我认为 BindingResult 是所有错误的通用容器。
标签: java spring-mvc code-formatting