Spring CustomNumberEditor解析不是数字的数字

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

  • 数字= 10 ……那么数字是10,没有错误
  • number = 10a ……那么数字是10,没有错误
  • number = 10a25 ……那么数字是10并且没有错误
  • number = a ……错误,因为该数字无效

因此,似乎编辑器会解析该值,直到它能够并省略其余的值。 有没有办法配置这个编辑器所以validation是严格的(所以数字像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 } 

你不能用NumberFormat做这个。

文档清楚地说明了这个事实:

 /** * Parses text from the beginning of the given string to produce a number. * The method may not use the entire text of the given string. * 

* See the {@link #parse(String, ParsePosition)} method for more information * on number parsing. * * @param source A String whose beginning should be parsed. * @return A Number parsed from the string. * @exception ParseException if the beginning of the specified string * cannot be parsed. */ public Number parse(String source) throws ParseException {

当您加入此API时,编写一个能够执行您想要的解析器并实现NumberFormat接口甚至是无效的。 这意味着您必须改为使用自己的属性编辑器。

 /* untested */ public class StrictNumberPropertyEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { super.setValue(Float.parseFloat(text)); } @Override public String getAsText() { return ((Number)this.getValue()).toString(); } } 

我认为最优雅的方法是使用NumberFormat.parse(String,ParsePosition) ,如下所示:

 public class MyNumberEditor extends PropertyEditorSupport { private NumberFormat f; public MyNumberEditor(NumberFormat f) { this.f = f; } public void setAsText(String s) throws IllegalArgumentException { String t = s.trim(); try { ParsePosition pp = new ParsePosition(0); Number n = f.parse(t, pp); if (pp.getIndex() != t.length()) throw new IllegalArgumentException(); setValue((Float) n.floatValue()); } catch (ParseException ex) { throw new IllegalArgumentException(ex); } } ... }