Announcement Announcement Module
Collapse
No announcement yet.
spring:bind error when converting empty input field to Long Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • spring:bind error when converting empty input field to Long

    I am using a SimpleFormController with Spring:bind tag on my jsp and a validator object.

    I have a simple Long property which maps to a simple input field, it validates numbers ok but if no value is entered at all it throws a conversion error.

    Please how do I handle this simple case, surely I dont have to write a property editor for this.

  • #2
    Where is it throwing? In the validator or in the view?

    Can you show us the code where it's throwing?

    Comment


    • #3
      By default, the CustomNumberEditor doesn't accept empty/null input. Put the following line in your controller initbinder() method:
      Code:
      binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));

      Comment


      • #4
        I tried that and was pretty confident it would solve the prpblem but it hasnt actually made any difference, the exact error I get is:
        Failed to convert property value of type [java.lang.String] to required type [java.lang.Long] for property 'volume'; nested exception is java.lang.NumberFormatException: For input string: " "

        Comment


        • #5
          Sorry I had only done a deploy not a real build, it has made a difference but code now falls over when I call ValidationUtils in my validator to validate the field, I will try subclassing the CustomNumberEditor

          Comment


          • #6
            ok, problem solved by creating the following class and registering it with initBinder
            Code:
            import org.springframework.beans.propertyeditors.CustomNumberEditor;
            import org.springframework.util.NumberUtils;
            import org.springframework.util.StringUtils;
            
            public class LongAllowsBlanksEditor extends CustomNumberEditor
            {
                public LongAllowsBlanksEditor()
                {
                    super(Long.class, true);
                }
            
                /**
                 * Parse the Number from the given text, using the specified NumberFormat.
                 */
                public void setAsText(String text) throws IllegalArgumentException
                {
                    super.setAsText(text);
                    if(getValue()==null)
                    {
                        setValue(new Long(0));            
                    }       
                }
            }

            Comment

            Working...
            X