【问题标题】:How validate a custom converter?如何验证自定义转换器?
【发布时间】:2011-11-06 03:09:24
【问题描述】:

我有一个自定义转换器是这样的:

@ManagedBean
@RequestScoped
public class MeasureConverter implements Converter {

    @EJB
    private EaoMeasure eaoMeasure;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Measure) || ((Measure) value).getId() == null) {
            return null;
        }

        return String.valueOf(((Measure) value).getId());
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {

        if (value == null || !value.matches("\\d+")) {
            return null;
        }

        Measure measure = eaoMeasure.find(Integer.valueOf(value));

        if (measure == null) {
            throw new ConverterException(new FacesMessage("Unknown Measure ID: " + value));
        }

        return measure;
    }

但我想像处理其他字段一样验证这一点,例如:

<h:outputLabel for="name" value="Name:" />
<h:inputText id="name" value="#{bean.name}">
<f:ajax event="blur" listener="#{validator.name}" render="m_name" />
</h:inputText>
<rich:message id="m_name" for="name" ajaxRendered="false" />

所以当blur 事件发生时,会出现一个图标,指示选择是否正确(上面的代码就是我所说的)

但我想在同一个自定义转换器中应用这种验证,只是为了通过我的项目对各种输入或种类保持标准验证。

我已经尝试在RequestScope 中使用@ManagaProperty 但没有成功:

@ManagedProperty("#{param.measure}")
private String measure;

因此,当模糊事件发生时,它会调用我的 validate bean,该 bean 具有如 BalusC 所说的 here 的 requestScope,但它出现的是一个空字符串。

有什么想法吗?

【问题讨论】:

    标签: jsf jsf-2


    【解决方案1】:

    你应该实现一个Validator

    例如

    @FacesValidator("measureValidator")
    public class MeasureValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            Measure measure = (Measure) value;
    
            // ...
    
            if (!valid) { 
                throw new ValidatorException(new FacesMessage("Not valid"));
            }
        }
    
    }
    

    可以通过输入组件的validator属性来声明

    <h:inputText validator="measureValidator">
    

    或者通过&lt;f:validator&gt;标签(是的,你可以有多个;它们将按照它们被附加到组件的顺序被调用)

    <h:inputText>
        <f:validator validatorId="measureValidator" />
    </h:inputText>
    

    转换器在这里不相关。它已经完成了将String 转换为Measure 的工作。验证器将只检索Measure。您在那里的@ManagedProperty 也不会那样工作。它基本上会设置request.getParameter("measure")结果的属性,我不认为你的表单提交了这样的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      相关资源
      最近更新 更多