我想实现自定义 validator ,在其中可以使用 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>
这是 validator :
@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));
}
}
}
这段代码工作正常。我还尝试实现此代码以便在 validator 中使用 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>
这是 validator :
@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));
}
}
}
由于某种原因,第二个示例不起作用。
最佳答案
你应该更具体一点,什么失败了?它不编译?它不运行?异常(exception)情况是什么,等等。而且还不清楚您在第二种情况下想要实现什么目标。
一般情况下,您不能通过在内部嵌套 f:attribute 来将属性传递给 f:validator。 让你的代码看起来像这样:
<f:validator binding="#{ValidatorController}" (session id in your case) />
<f:attribute name="type" value="sessionid" />
稍后您可以在组件参数Map中搜索组件参数:
context.getExternalContext().getRequestParameterMap();
关于java - 如何使用 CDI 创建 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10534111/