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

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

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

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

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

注册编辑器的方式是:

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

谢谢.

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

第一次脸红了

public class StrictFloatNumberFormat extends NumberFormat {

  private void validate(in) throws ParseException{
     try {
       new Float(in);
     }
     catch (NumberFormatException nfe) {
       throw new ParseException(nfe.getMessage(),0);     
  }


  public Number parse(String in) throws ParseException {
    validate(in);
    super.parse(in);
  }
  ..... //any other methods
}
原文链接:https://www.f2er.com/spring/431845.html

猜你在找的Spring相关文章