Monday, May 18, 2009

JSF input - empty value converted to Zero

When running a JSF application under Tomcat, you might encounter a weird case in which an empty value of a field bidden with numeric property (like Integer) is converted to zero instead of remaining "null".

Consider the following case, in which text field is used to input Integer value:

<h:inputText id="myInput" value="#{myBean.myInteger}" converter="IntegerConverter" />

And the bean holding the value:

package com.bashan.blog.jsf;
public class MyBean {
  private Integer myInteger;
  public Integer getMyInteger() {
    return myInteger;
  }
  public void setMyInteger(Integer myInteger) {
    this.myInteger = myInteger;
  }
}
Apparently, Tomcat is coercing “null” values to zeroes. This behavior can be disabled by setting the following JVM parameter to "false":
-Dorg.apache.el.parser.COERCE_TO_ZERO=false

By default the “true” value is used. By setting this value to “false” Tomcat will no longer try to coerce value expressions.

You can also set this parameter in Java code. This may be a better idea, if you don’t want to remember to set this parameter on each new environment you deploy your web application. Here is how it can be done:

System.getProperties().put("org.apache.el.parser.COERCE_TO_ZERO", "false");

You can run this code when your server first loads in some initialization Servlet.

If I recall correct, this behavior was changed sometime along the development of Tomcat. That means you can experience different behaviors on different environments of Tomcat. For example, Production environment behaves differently from Development environment, since there are 2 distinct versions of Tomcat. This may cause a bit confusion, when trying to identify the problem.

3 comments:

  1. I tried the second way
    System.getProperties().put("org.apache.el.parser.COERCE_TO_ZERO", "false");
    but its not working for me..

    and dint get about the first solution (-Dorg.apache.el.parser.COERCE_TO_ZERO=false)
    where should i specify the parameter
    by where i mean in which file of tomcat..
    and in which section

    please reply ...

    ReplyDelete
  2. Where did you call the: System.getProperties().put("org.apache.el.parser.COERCE_TO_ZERO", "false"); ?

    In the first solution you should set the value as JVM parameter. If you are working with Windows and has Tomcat installed as a service, you can click on the Tomcat systray icon, then move to the Java tab and simply paste this value on the "Java Options" text area:
    -Dorg.apache.el.parser.COERCE_TO_ZERO=false

    ReplyDelete
  3. Thank you. Helps me a lot!

    ReplyDelete