PDA

View Full Version : CustomNumberEditor: how to overrule error messages


huijzer
Apr 27th, 2006, 09:00 AM
Hi all,

I have registered a CustomNumberEditor in my Controller that enables me to have optional Integer properties.

protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {

PropertyEditor editor = new CustomNumberEditor(Integer.class, true);
binder.registerCustomEditor(Integer.class, "year", editor);
}

Everything works as expected, but when I type an invalid value in the HTML form, I get the following error message shown in my form:


Failed to convert property value of type [java.lang.String] to required type [java.lang.Integer] for property year; nested exception is java.lang.NumberFormatException: For input string: "invalid"


Is there a way that I can override this message and have a error message from my messages.properties (I have this configured in a MessageSource bean) file shown?

Thanks in advance,

Arjan Huijzer

tobysaville
Apr 28th, 2006, 04:32 AM
You need to set up an application resource message bundle in your applicationContext.xml:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundle MessageSource">
<property name="basenames">
<list>
<value>path/to/errors</value>
</list>
</property>
</bean>

Then in your file named path.to.errors.properties, place the following key for each type of bind class that you want a custom message for:

typeMismatch.java.lang.Integer=My tidy error message for integers
typeMismatch.java.lang.Double=My tidy error message for doubles

etc...

cheers, toby

huijzer
Apr 28th, 2006, 09:36 AM
That was exactly what I was looking for. Worked perfectly!

shahzad992
May 2nd, 2006, 02:04 AM
hi,
i have also done this. but i want more, as my page is containing more the 5 number fields.And i want to show the message with proptery name containing the number format error.

Regards,
Shahzad

EndlessWinter
May 2nd, 2006, 05:33 AM
typeMismatch.java.lang.Integer={0} should be integer
?
If this is not enough, this javadoc might help:
http://www.springframework.org/docs/api/org/springframework/validation/DefaultMessageCodesResolver.html

huijzer
May 3rd, 2006, 07:13 AM
I have implemented this solution and the "{0}" part gets correctly filled with the name of the field that caused the error. The next question I have is this: how can I get Spring to use a user defined label to replace the "{0}" instead of the field name?

Thanks in advance for any help,

Arjan Huijzer

EndlessWinter
May 3rd, 2006, 08:51 AM
in the same javadoc there is a description of message resolution for property names. The simplest is
someField = the description of the filed
or
outerObject.someFiled = the description of the filed
Also, don't forget, that message resolution properly works inside corresponding <spring:bind>, when you are operationg with Error object