推荐淘宝秋冬男装热卖网店

追求无止境

我的程序人生
随笔 - 31, 文章 - 2, 评论 - 20, 引用 - 0
数据加载中……

Spring MVC 框架学习笔记之BaseCommandController和AbstractCommandController

 

Spring的BaseCommandController继承自AbstractController。在看BaseCommandController之前先看他的继承类AbstractCommandController是如何实现

AbstractController的handleInternalRequest方法的:

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object command = getCommand(request);
ServletRequestDataBinder binder = bindAndValidate(request, command);
BindException errors = new BindException(binder.getBindingResult());
return handle(request, response, command, errors);
}

getCommand就是BaseCommandController中的方法。

protected Object getCommand(HttpServletRequest request) throws Exception {
return createCommand();
}
protected final Object createCommand() throws Exception {
if (this.commandClass == null) {
throw new IllegalStateException("Cannot create command without commandClass being set - " +
"either set commandClass or (in a form controller) override formBackingObject");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating new command of class [" + this.commandClass.getName() + "]");
}
return BeanUtils.instantiateClass(this.commandClass);
}

createCommand创建了一个CommandClass的对象。

然后再看bindAndValidate方法:

protected final ServletRequestDataBinder bindAndValidate(HttpServletRequest request, Object command)
throws Exception {
ServletRequestDataBinder binder = createBinder(request, command);
BindException errors = new BindException(binder.getBindingResult());
if (!suppressBinding(request)) {
binder.bind(request);
onBind(request, command, errors);
if (this.validators != null && isValidateOnBinding() && !suppressValidation(request, command, errors)) {
for (int i = 0; i < this.validators.length; i++) {
ValidationUtils.invokeValidator(this.validators[i], command, errors);
}
}
onBindAndValidate(request, command, errors);
}
return binder;
}

这个方法首先创建了 DataBinder对象,然后,获取创建绑定对象时发生的错误。报错在errors。接下来绑定对象,调用onBind处理绑定事件;接下来应用Validator。然后调用onBindAndValidate来处理绑定和验证事件。最后返回binder。

处理完之后调用handle方法进行处理。

综上所述,AbstractCommandController具有两个功能:

1、将请求参数转换为Command对象。在该Controller中,我们设置一个object对象。然后BaseCommandController将请求的参数进行转换。如果请求参数有value值,就会调用object的的setValue对象来设置对象里的值。如果请求参数中有address.city.就会调用object中getAddress().setCity()方法来赋值。这个object可以是任意的object,唯一的要求就是这个object类没有参数。

2、对数据进行验证。在转换和验证时发生错误时,需要在handle(request, response, command, errors)中进行处理。

posted on 2009-11-25 16:25 追求无止境 阅读(5347) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: