我想实现可在其中使用CDI和数据源的自定义验证器。我测试了这段代码:
<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
<f:validateLength minimum="0" maximum="15"/>
<f:validator validatorId="ValidatorController" >
</f:validator>
<f:ajax event="blur" render="sessionidMessage" />
</h:inputText>
<h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>
这是验证器:
@FacesValidator("ValidatorController")
public class FormValidator implements Validator {
public FormValidator() {
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value.equals("test")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Session ID is already in use, please choose another.", null));
}
}
}
此代码可以正常工作。我还尝试实现此代码,以便在验证器中使用CDI:
<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
<f:validateLength minimum="0" maximum="15"/>
<f:validator binding="#{ValidatorController}" >
<f:attribute name="type" value="sessionid" />
</f:validator>
<f:ajax event="blur" render="sessionidMessage" />
</h:inputText>
<h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>
这是验证器:
@Named("ValidatorController")
public class FormValidator implements Validator {
public FormValidator() {
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value.equals("test")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Session ID is already in use, please choose another.", null));
}
}
}
由于某些原因,第二个示例不起作用。
最佳答案
您应该更具体些,什么失败?它不编译吗?它不运行?有什么例外,等等。也不清楚您在第二种情况下要达到的目标。
通常,不能通过嵌套f:attribute insside将属性传递给f:validator。
使您的代码如下所示:
<f:validator binding="#{ValidatorController}" (session id in your case) />
<f:attribute name="type" value="sessionid" />
稍后,您可以在组件参数Map中搜索组件参数:
context.getExternalContext().getRequestParameterMap();