JSF: Accessing Bean from Validator via field

后端 未结 2 435
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 00:26

I have a JSF validator that checks whether a Container Number string conforms to the ISO-6346 specficiation.

It works fine, however I need to add some conditional p

相关标签:
2条回答
  • 2020-12-21 00:46

    You can use the following to get any old bean you like using the FacesContext. Very similar to the solution you found.

    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() );
    }
    
    0 讨论(0)
  • 2020-12-21 00:54

    Using the <f:attribute> you can pass a Bean to the validator and retrieve it from the component as a value expression.

    So my input is like this (must be using <f:validator> and not the validator attribute on the <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>
    

    And my validator class:

    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
      }
    
    0 讨论(0)
提交回复
热议问题