我在输出java.math.BigDecimal时创建了自定义Converter。当BigDecimal为0.00或null
时,我想输出破折号。
这是我的XHTML
<p:dataTable value="#{bean.data}" var="item">
<p:column>
<h:outputText value="#{item.currentValue}">
<f:converter converterId="my.bigDecimalConverter" />
</h:outputText>
</p:column>
</p:dataTable>
我遇到的问题是当#{item.currentValue}为null
时,转换器中的getAsString
方法未被调用。
@FacesConverter("my.bigDecimalConverter")
public class BigDecimalConverter implements Converter {
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (context == null || component == null) {
throw new NullPointerException();
}
if (value == null) {
System.out.println("null=");
return "--";
}
System.out.print("Class=" + value.getClass());
if (value instanceof String) {
System.out.println("Str=" + value);
return (String) value;
}
if (value instanceof BigDecimal) {
BigDecimal bd = (BigDecimal)value;
if (bd.equals(new BigDecimal("0.00"))) {
return "--";
} else {
return bd.toPlainString();
}
}
return "";
}
}
我说它没有被调用,因为当BigDecimal为println
时,我没有错误,也没有null
语句输出。当BigDecimal不是null
时,它按预期工作,&#34; Class = class java.math.BigDecimal&#34; 被打印出来,当BigDecimal为0.00时,我得到{ {1}}在页面上输出。
我使用的是JSF 2.1,Mojarra 2.1.27
我还使用以下方法测试我的转换器。
--
阅读这个问题,似乎转换器应该使用<h:outputText value="#{null}">
<f:converter converterId="my.bigDecimalConverter" />
</h:outputText>
值。
https://stackoverflow.com/a/19093197/50262
答案 0 :(得分:6)
您发布的链接表明转换器应该使用null但不要说在每种情况下都会使用空值调用转换器。
具体地说,当h:outputText
内的并且值为空时,它不会调用转换器。
如果你深入了解Mojarra来源,你会看到:
//Line 355 -- com.sun.faces.renderkit.html_basic.HtmlBasicRenderer
//method getCurrentValue
Object currentObj = getValue(component);
if (currentObj != null) {
currentValue = getFormattedValue(context, component, currentObj);
}
很明显,永远不会转换空值!而且我找不到解决方法。
然后,如果您确实需要您的值为null(您可以返回0或其他)我认为您唯一的机会是制作自定义渲染器。这很容易:
您编写的渲染器会覆盖重要的方法:
package my;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import com.sun.faces.renderkit.html_basic.TextRenderer;
public class HtmlCustomRenderer extends TextRenderer {
@Override
public String getCurrentValue(FacesContext context, UIComponent component) {
if (component instanceof UIInput) {
Object submittedValue = ((UIInput) component).getSubmittedValue();
if (submittedValue != null) {
// value may not be a String...
return submittedValue.toString();
}
}
String currentValue = null;
Object currentObj = getValue(component);
//Remove the 'if' to call getFormattedValue even if null
currentValue = getFormattedValue(context, component, currentObj);
return currentValue;
}
}
然后我们在faces-config.xml中声明渲染器:
<render-kit>
<renderer>
<component-family>javax.faces.Output</component-family>
<renderer-type>javax.faces.Text</renderer-type>
<renderer-class>my.HtmlCustomRenderer</renderer-class>
</renderer>
</render-kit>
现在您的转换器将使用空值调用!
我希望它会有所帮助!