java – Spring CustomNumberEditor解析不是数字的数字

前端之家收集整理的这篇文章主要介绍了java – Spring CustomNumberEditor解析不是数字的数字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用Spring CustomNumberEditor编辑器来绑定我的浮点值,并且我已经尝试过,如果值不是数字,有时它可以解析该值并且不返回任何错误.

>数字= 10 ……然后数字是10,没有错误
> number = 10a ……那么数字是10,没有错误
> number = 10a25 ……那么数字是10,没有错误
> number = a ……错误,因为该号码无效

所以似乎编辑器会解析它的值,直到它能够并省略其余的值.有没有办法配置这个编辑器所以验证是严格的(所以数字像10a或10a25导致错误)或我是否必须构建我的自定义实现.我在CustomDateEditor / DateFormat中看起来像设置lenient为false,因此无法将日期解析为最可能的日期.

注册编辑器的方式是:

  1. @InitBinder
  2. public void initBinder(WebDataBinder binder){
  3. NumberFormat numberFormat = NumberFormat.getInstance();
  4. numberFormat.setGroupingUsed(false);
  5. binder.registerCustomEditor(Float.class,new CustomNumberEditor(Float.class,numberFormat,true));
  6. }

谢谢.

最佳答案
由于它依赖于NumberFormat类,它停止在第一个无效字符处解析输入字符串,我认为你必须扩展NumberFormat类.

第一次脸红了

  1. public class StrictFloatNumberFormat extends NumberFormat {
  2. private void validate(in) throws ParseException{
  3. try {
  4. new Float(in);
  5. }
  6. catch (NumberFormatException nfe) {
  7. throw new ParseException(nfe.getMessage(),0);
  8. }
  9. public Number parse(String in) throws ParseException {
  10. validate(in);
  11. super.parse(in);
  12. }
  13. ..... //any other methods
  14. }

猜你在找的Spring相关文章