我只想测试@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>


怎么了

最佳答案

@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扩展并委托给它。您可以在下面的链接中找到一些具体示例,这些问题与相关问题密切相关。
也可以看看:

validating decimals inputs in JSF
Need <f:convertNumber> to throw error when fractions or separator characters are used
convertNumber shows 0,00 as a negative value
How to standardize convertnumber usage in JSF for various components?

关于jsf - @FacesConverter forClass-Attribute不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39439917/

10-12 18:52