有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java处理定制Spring验证器绑定到输入字段的LongValue是否为时已晚?

部分(Java、SpringMVC、JSP)表单输入由Javascript检查。其余部分由自定义验证器完成。 问题是,当阻止Javascript验证时,可能会打印出这样的错误:

Failed to convert property value of type java.lang.String to required type java.lang.Long for property xxx; nested exception is java.lang.NumberFormatException: For input string: "x"

是否有更好的方法来处理转换本身。当Java验证器运行时,它已经遇到了转换错误——或者是否有可能在此之前进行检查


编辑:控制器内活页夹的代码

@InitBinder
public void initBinder(WebDataBinder binder) {
   SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
   dateFormat.setLenient(false);

   binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
   binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
}

但它实际上只是标准功能(org.springframework.beans.propertyeditors.CustomNumberReditor),我认为必须有一个简单的解决方案,因为让一个长对象支持某个输入字段并试图从中获得任何异常(或捕获该字段)似乎是一件常见的事情


共 (2) 个答案

  1. # 1 楼答案

    如果有人感兴趣。。最终起作用的定制活页夹代码如下

      // prevent alphanumeric/special chars in numeric string (for backing field of type Long)
      binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true) {
         @Override
         public void setAsText(String value) {
            if (value != null && !value.isEmpty() && CustomValidator.isNumeric(value)) {
               super.setAsText(value);
            } else {
               super.setAsText(null);
            }
         }
      });
    

    尽管如此,您仍然需要调整验证方法,以便对输入、删除并更改为空的文本有意义

  2. # 2 楼答案

    似乎需要在控制器中实现一个绑定器,以便从String转换为Long。看看this thread是否有用,它提供了将字符串转换为Long的代码

    更新

    binder.registerCustomEditor(Long.class, "myFieldName", new  PropertyEditorSupprt(){
        @Override
        public void setValue(Object value) {
            if(value instanceof String)
               super.setValue(new Long(value));      
        }
    
    });