以 BaseCommandController 為例
protected void initApplicationContext() {
if (this.validators != null) {
for (int i = 0; i < this.validators.length; i++) {
if (this.commandClass != null && !this.validators[i].supports(this.commandClass))
throw new IllegalArgumentException("Validator [" + this.validators[i] +
"] does not support command class [" +
this.commandClass.getName() + "]");
}
}
}
子類配置如下
<bean id="addNewsController" class="AddNewsController" scope="request">
<property name="formView" value="/management/news/addNews"/>
<property name="validator" ref="beanValidator"/>
<property name="successView" value="forward:/management/news/newsList.html"/>
<property name="commandClass" value="News"/>
<property name="commandName" value="news"/>
</bean>
public final void setValidator(Validator validator) {
this.validators = new Validator[] {validator};
}
設(shè)置Validator數(shù)組
在初始化的時(shí)候,檢驗(yàn) 是否支持command 類型
this.validators[i].supports(this.commandClass)
此support 為 org.springframework.validation.Validator 的所有 實(shí)現(xiàn)類的 方法,檢驗(yàn)支持檢驗(yàn)類的動(dòng)作。
舉例 配置
<bean id="beanValidator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>
DefaultBeanValidator extends AbstractBeanValidator implements Validator
再看實(shí)現(xiàn)方法
/**
* Checks if the validatorFactory is configured to handle this class. Will
* convert the class into a form name, suitable for commons validator.
*
* @return <code>true</code> if the validatorFactory supports the class,
* or <code>false</code> if not
* @see #getFormName(Class)
*/
public boolean supports(Class clazz) {
boolean canSupport = validatorFactory.hasRulesForBean(getFormName(clazz), getLocale());
if (log.isDebugEnabled()) {
log.debug("validatorFactory " + (canSupport ? "does" : "does not")
+ " support class " + clazz + " with form name " + getFormName(clazz));
}
return canSupport;
}
檢驗(yàn)是否支持輸入類
另一個(gè)方法
/**
* If <code>useFullyQualifiedClassName</code> is false (default value), this function returns a
* string containing the uncapitalized, short name for the given class
* (e.g. myBean for the class com.domain.test.MyBean). Otherwise, it returns the value
* returned by <code>Class.getName()</code>.
*
* @param cls <code>Class</code> of the bean to be validated.
* @return the bean name.
*/
protected String getFormName(Class cls) {
return (this.useFullyQualifiedClassName) ? cls.getName() : Introspector.decapitalize(ClassUtils.getShortName(cls));
}
Introspector.decapitalize(ClassUtils.getShortName(cls) 獲得按照西班牙命名法的form 名
這個(gè)方法本意是獲得以類名為formName 的所有校驗(yàn)配置。
實(shí)際上有一個(gè)重大的設(shè)計(jì)缺陷