JSF:通过字段从Validator访问Bean

Dam*_*amo 5 java jsf

我有一个JSF验证器,用于检查Container Number字符串是否符合ISO-6346规范.

它工作正常,但我需要根据容器号来自的Bean中的其他值添加一些条件处理.这个Bean可以有几种不同的类型.

有没有办法在验证器中访问Bean并对其执行操作?理想情况下,我喜欢将它作为验证器,但如果没有解决方案,我必须在持久化之前在Bean中实现逻辑.

我正在考虑以下几点:

public class ContainerNumberValidator implements javax.faces.validator.Validator {
   public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

      Object bean = UIComponent.getMyBeanSomehowThroughAMagicMethod();
      if(bean instanceof BeanA) {
         //do this
      } else if(bean instanceof BeanB) {
         //do that
      }
}
Run Code Online (Sandbox Code Playgroud)

更新:在许多方面,这是同时验证多个字段的类似问题.BalusC的这段代码很有帮助.

非常感激.

D.

Dam*_*amo 5

使用< f:attribute>您可以将Bean传递给验证器并从组件中将其作为值表达式检索.

所以我的输入是这样的(必须使用<f:validator>而不是验证器属性<h:inputText>):

<h:inputText id="containerNum" size="20" maxlength="20" value="#{containerStockAction.containerStock.containerNumber}">
    <f:validator validatorId="containerNumberValidator" />
    <f:attribute name="containerBean" value="#{containerStockAction.containerStock}"/>
</h:inputText>
Run Code Online (Sandbox Code Playgroud)

我的验证器类:

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
  String containerNumber = (String)value;
  Object containerBean = component.getValueExpression("containerBean").getValue(context.getELContext());

  if(containerBean instanceof BeanA) {
    //do this
  }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 5

您可以使用以下方法通过 FacesContext 获取您喜欢的任何旧 bean。与您找到的解决方案非常相似。

public void validate(FacesContext context, UIComponent component, Object value)
{
    Application app = context.getApplication();

    ValueExpression expression = app.getExpressionFactory().createValueExpression( context.getELContext(),
            "#{thingoBean}", Object.class );

    ThingoBean thingoBean = (ThingoBean) expression.getValue( context.getELContext() );
}
Run Code Online (Sandbox Code Playgroud)