View Full Version : Error on binding an int field
jamin
Mar 29th, 2007, 05:51 AM
I get the following error when submitting my form.
Failed to convert property value of type [java.lang.String] to required type [int] for property 'alerts[0].alertHour'; nested exception is java.lang.NumberFormatException: For input string: "8"
The entered value for the 'alerts[0].alertHour' property is '08'. If i enter '8' the binding error is not produced. If i enter values '00', '01' up to '07' i dont see the error either. Its just with values '08' and '09'.
Anyone got any ideas about whats going on?
Andreas Senft
Mar 29th, 2007, 06:42 AM
In Java integer literals with leading "0" are considered to be in octal format. And since in octal the highest digit is "7", the conversion fails for "08" and "09".
Similarly, literals beginning with "0x" are considered to be in hexadecimal format.
Regards,
Andreas
jamin
Mar 29th, 2007, 06:48 AM
Ah right.
So i guess i need to create a editor for the fields and strip the leading '0' if present.
Thank you.
Andreas Senft
Mar 29th, 2007, 07:09 AM
So i guess i need to create a editor for the fields and strip the leading '0' if present.
I think that should do the trick. Just wondering about how many websites there might be which might have such an octal conversion problem...
Thank you.
You're welcome. :)
jamin
Mar 29th, 2007, 07:16 AM
This seems to work ok...
public class IntegerPropertyEditor extends PropertyEditorSupport
{
@Override
public void setAsText(String text) throws IllegalArgumentException
{
setValue(Integer.parseInt(text, 10));
}
}
binder.registerCustomEditor(int.class, new IntegerPropertyEditor());
Just wondering about how many websites there might be which might have such an octal conversion problem...
An interesting question... I ran into this issue because my site is dealing with times. So it seems logical to me ( but maybe not anyone else ) that someone might enter '08' for the hour value.
Andreas Senft
Mar 29th, 2007, 07:23 AM
As alternative you might also use org.springframework.beans.propertyeditors.CustomNu mberEditor. Providing a pattern of "00" should work as well.
Regards,
Andreas
irus
Mar 29th, 2007, 11:31 AM
Refer this thread (http://forum.springframework.org/showthread.php?t=36706). Similar issue is dealt at length. The only difference I see is in your case the field is integer and this thread talks about long fields in command objects.
If you want the user to allow inputting numbers like "01" etc., then probably you have to use "propertyeditors" ....
vBulletin® v3.7.3, Copyright ©2000-2008, Jelsoft Enterprises Ltd.