Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jsf - h:inputText which is bound to String property is submitting empty string instead of null

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>

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; }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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();
    }

}

...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>

In case you're not on Java 6 yet, replace submittedValue.empty() by submittedValue.length() == 0.

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...