我只想测试@FacesConverter
-功能,并被困在forClass
-属性上-它不起作用-这是我的例子:
转换类:
@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)
仅适用于尚未内置转换器存在的自定义类型。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>
顺便说一下,考虑从DoubleConverter
或NumberConverter
扩展并委托给它。你可以在下面的链接中找到一些相关问题的具体例子。
参见:
- 验证JSF中的小数输入
- 需要& lt; f: convertNumber>当使用分数或分隔符时抛出错误
- convertNumber显示0,000为负值
- 如何标准化JSF中各种组件的转换数使用?