@FacesConverter forClass-Attribute不起作用

时间:2016-09-11 19:37:06

标签: jsf converter

我想测试@FacesConverter - 功能并加入forClass - atrribute - 它不起作用 - 这是我的例子:

转换器类:

@FacesConverter(forClass = Double.class)
public class TextToDoubleConverter implements Converter {

    @Override
    public Double getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        Double doubledValue = null;
        try {
            doubledValue = new Double(value);
        } catch (NumberFormatException e) {
            FacesMessage facesMessage = new FacesMessage("Fehler: ...");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return doubledValue;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return value.toString();
    }

}

ManagedBean:

@Model
public class SomeBean {


    private Double someCommvertDouble;


    public Double getSomeCommvertDouble() {
        return someCommvertDouble;
    }

    public void setSomeCommvertDouble(Double someCommvertDouble) {
        this.someCommvertDouble = someCommvertDouble;
    }
}

的index.xhtml:

    <h:form>
    <h:inputText value="#{someBean.someCommvertDouble}">
<!--        <f:converter converterId="com.java.ee.jsf.TextToIntConverter"/>  -->    
 </h:inputText>

    </h:form>

这里有什么问题?

1 个答案:

答案 0 :(得分:2)

@FacesConverter(forClass)仅适用于尚未存在built-in converter的自定义类型。 Double类型已经有内置转换器DoubleConverter。已在faces-config.xml中定义的任何转换器(例如内置转换器)将始终优先于使用@FacesConverter注释的转换器。

只有您在webapp的faces-config.xml中明确注册,而不是注释时,您的转换器才有效。

<converter>
    <converter-for-class>java.lang.Double</converter-for-class>
    <converter-class>com.example.YourDoubleConverter</converter-class>
</converter>

顺便提一下,请考虑从DoubleConverterNumberConverter延伸并委托给它。您可以在下面找到一些具体的例子,链接到密切相关的问题。

另见: