i wrote custom spring formatter (which implements org.springframework.format.formatter
interface) converting form input values bigdecimal
values dollar inputs. formatter not accept values more 2 digits after decimal place. in case, parseexception
thrown formatter's parse()
method.
public class inputdollarbigdecimalformatter implements formatter<bigdecimal> { @override public bigdecimal parse(string text, locale locale) throws parseexception { // ... } @override public string print(bigdecimal amount, locale locale) { // ... } }
the formatter registered can applied using annotation named @inputdollarbigdecimalformat
.
a field in form-backing object, formatter applied, looks this:
@inputdollarbigdecimalformat private bigdecimal price;
the formatter working fine.
the problem when parseexception
thrown, spring still attempts convert input value bigdecimal
using default conversion. means input value of 100.123
still converted bigdecimal
, though custom formatter throws parseexception
.
how can prevent spring converting input value bigdecimal
when custom formatter has rejected value throwing parseexception
?
i'm using spring 3.1.0.
spring formatters documented here.
update:
after stepping through code debugger, see logic in org.springframework.beans.typeconverterdelegate
class. spring doing on purpose, can see following possible solutions:
(1) if possible, un-register default propertyeditor
bigdecimal
values. appears spring registers org.springframework.beans.propertyeditors.customnumbereditor
converting string bigdecimal
. of course, solution has downside default propertyeditor
not available other bigdecimal
fields (that not use custom formatter).
(2) create dollar
class wraps bigdecimal
, change custom formatter work dollar
class. type of field have change dollar
. bit of nuisance when working values.
(3) perhaps spring has realized incorrect fall default propertyeditor
when custom formatter has rejected value , has been changed in more recent version of spring. i'm doubtful, if knows either way, appreciated.
(4) perhaps correct solution view custom formatter helping out default propertyeditor
allowing more formats. in addtion limiting value 2 decimal places, custom formatter allows input value include dollar sign , commas. leave logic, remove decimal place restriction. add custom bean validation (jsr 303) constraint rejects value if not have 2 digits after decimal place (unless has none). have annotate field constraint:
@inputdollarbigdecimalformat @wholedollarorcentsconstraint private bigdecimal price;
of course, have add error message constraint, in addition 1 formatter.
if of these seems correct solution you, feel free add answer reasoning.
Comments
Post a Comment