问题描述
我在Tomcat上有一个JSF 2.0应用程序,其中有许多<h:inputText>
字段用于在数据库中输入数据.某些字段不是必需的.
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; }
推荐答案
您可以将JSF 2.x配置为通过web.xml
中的以下context-param
将空提交的值解释为null(名称很长,即也将是为什么我不记得它的原因;)):
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
解决: /p>
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
.
这篇关于h:inputText绑定到String属性正在提交空字符串而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!