Spring CustomNumberEditor解析不是数字的数字

Jav*_*avi 5 java data-binding spring spring-mvc propertyeditor

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

  • number = 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));
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ral*_*lph 7

你不能用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.
 * <p>
 * See the {@link #parse(String, ParsePosition)} method for more information
 * on number parsing.
 *
 * @param source A <code>String</code> whose beginning should be parsed.
 * @return A <code>Number</code> parsed from the string.
 * @exception ParseException if the beginning of the specified string
 *            cannot be parsed.
 */
public Number parse(String source) throws ParseException {
Run Code Online (Sandbox Code Playgroud)

当您加入此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();
    }    
}
Run Code Online (Sandbox Code Playgroud)


小智 4

由于它依赖于 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
}
Run Code Online (Sandbox Code Playgroud)