绑定到 String 属性的 h:inputText 提交的是空字符串而不是 null [英] h:inputText which is bound to String property is submitting empty string instead of null
问题描述
我在 Tomcat 上有一个 JSF 2.0 应用程序,其中有许多
字段用于在我的数据库中输入数据.某些字段不是必需的.
I have a JSF 2.0 application on Tomcat with many <h:inputText>
fields to input data in my database. Some fields are not required.
<h:inputText value="#{registerBean.user.phoneNumber}" id="phoneNumber">
<f:validateLength maximum="20" />
</h:inputText>
当用户将此字段留空时,JSF 设置空字符串 ""
而不是 null
.
When the user leave this field empty JSF sets empty string ""
instead of null
.
如何在不检查每个字符串的情况下修复此行为
How can I fix this behavior without checking every String with
if (string.equals("")) { string = null; }
推荐答案
您可以通过 web.xml 中的以下
(它的名字很长,这也是我想不起来的原因;)):context-param
配置 JSF 2.x 以将空提交的值解释为 null.xml
You can configure JSF 2.x to interpret empty submitted values as null by the following context-param
in web.xml
(which has a pretty long name, that'll also be why I couldn't recall it ;) ):
<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 或更早版本,因为设计上不可能有 java.lang.String
Converter 的Converter
code>) 这可以通过以下 Converter
解决:
For reference and for ones who are interested, in JSF 1.2 (and thus not 1.1 or older because it's by design not possible to have a Converter
for java.lang.String
) this is workaroundable with the following 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
中注册如下:
...which needs to be registered in faces-config.xml
as follows:
<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
.
In case you're not on Java 6 yet, replace submittedValue.empty()
by submittedValue.length() == 0
.
这篇关于绑定到 String 属性的 h:inputText 提交的是空字符串而不是 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!