context-param
您可以配置 JSF 2.x 以通过以下方式将空提交的值解释为 null web.xml
(它的名称很长,这也是我记不起它的原因;)):
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
作为参考和感兴趣的人,在 JSF 1.2 中(因此不是 1.1 或更早版本,因为设计上不可能有Converter
for java.lang.String
),这可以通过以下方式解决Converter
:
public class EmptyToNullStringConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
if (component instanceof EditableValueHolder) {
((EditableValueHolder) component).setSubmittedValue(null);
}
return null;
}
return submittedValue;
}
public String getAsString(FacesContext facesContext, UIComponent component, Object modelValue) {
return (modelValue == null) ? "" : modelValue.toString();
}
}
...需要注册faces-config.xml
如下:
<converter>
<converter-for-class>java.lang.String</converter-for-class>
<converter-class>com.example.EmptyToNullStringConverter</converter-class>
</converter>
如果您还没有使用 Java 6,请替换submittedValue.empty()
为submittedValue.length() == 0
.
也可以看看