11

I know there are a number of posts about converting empty string to null in JSF2. The usual prescription is to add the following to web.xml.

<context-param>
  <description>Does not appear to work</description>
  <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
  <param-value>true</param-value>
</context-param>

This just does not seem to work - at all. I then created a custom string converter to test if that would work. I explicitly added it as a converter to my inputText (otherwise it does not fire when blank).

When INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL is set to true the converter receives null and the setter for the input text still receives "".

When INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL is set to false (or commented out) the converter receives "" and the setter for the input text receives "" (even after the converter returns null).

@FacesConverter(forClass=java.lang.String.class, value="emptyStringToNull")
public class StringConverter implements Converter, Serializable {
    private static final long serialVersionUID = -1121162636180944948L;
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        return value;
    }

    public String getAsString(FacesContext context, UIComponent component, Object object) {
    if (object == null)
        return null;

    return object.toString();
    }
}

I've event tried (to no avail) to explicitly set the component submitted value in getAsObject:

if (component instanceof EditableValueHolder)
    ((EditableValueHolder) component).setSubmittedValue(null);

I'm using JBoss6 (a snapshot of 6.1 really) and JSF 2.1.1.

4

1 回答 1

21

This is not Mojarra specific. This is Tomcat specific (JBoss uses Tomcat as servletcontainer). Add the following VM argument to startup options.

-Dorg.apache.el.parser.COERCE_TO_ZERO=false

To my experience, this one should actually only apply on Number properties (int, long, etc), however since a certain late Tomcat 6.0.x version (at least after 6.0.20) it seems to be broken for strings as well and it is relying on the above VM argument.

On GlassFish 3.x for example it works perfectly fine out the box.

于 2011-06-10T12:08:07.550 回答