Spring MVC 框架學(xué)習(xí)筆記之BaseCommandController和AbstractCommandController
Spring的BaseCommandController繼承自AbstractController。在看BaseCommandController之前先看他的繼承類(lèi)AbstractCommandController是如何實(shí)現(xiàn)
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創(chuàng)建了一個(gè)CommandClass的對(duì)象。
然后再看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; }
這個(gè)方法首先創(chuàng)建了 DataBinder對(duì)象,然后,獲取創(chuàng)建綁定對(duì)象時(shí)發(fā)生的錯(cuò)誤。報(bào)錯(cuò)在errors。接下來(lái)綁定對(duì)象,調(diào)用onBind處理綁定事件;接下來(lái)應(yīng)用Validator。然后調(diào)用onBindAndValidate來(lái)處理綁定和驗(yàn)證事件。最后返回binder。
處理完之后調(diào)用handle方法進(jìn)行處理。
綜上所述,AbstractCommandController具有兩個(gè)功能:
1、將請(qǐng)求參數(shù)轉(zhuǎn)換為Command對(duì)象。在該Controller中,我們?cè)O(shè)置一個(gè)object對(duì)象。然后BaseCommandController將請(qǐng)求的參數(shù)進(jìn)行轉(zhuǎn)換。如果請(qǐng)求參數(shù)有value值,就會(huì)調(diào)用object的的setValue對(duì)象來(lái)設(shè)置對(duì)象里的值。如果請(qǐng)求參數(shù)中有address.city.就會(huì)調(diào)用object中g(shù)etAddress().setCity()方法來(lái)賦值。這個(gè)object可以是任意的object,唯一的要求就是這個(gè)object類(lèi)沒(méi)有參數(shù)。
2、對(duì)數(shù)據(jù)進(jìn)行驗(yàn)證。在轉(zhuǎn)換和驗(yàn)證時(shí)發(fā)生錯(cuò)誤時(shí),需要在handle(request, response, command, errors)中進(jìn)行處理。
posted on 2009-11-25 16:25 追求無(wú)止境 閱讀(5390) 評(píng)論(0) 編輯 收藏