加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:32:29 所属栏目:大数据 来源:网络整理
导读:我正在使用Spring CustomNumberEditor编辑器来绑定我的浮点值,并且我已经尝试过,如果值不是数字,有时它可以解析该值并且不返回任何错误. 数字= 10 然后数字是10,没有错误 number = 10a 那么数字是10,没有错误 number = 10a25 那么数字是10,没有错误 number =

我正在使用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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读