【发布时间】:2013-02-09 16:30:06
【问题描述】:
我正在使用 Spring 3.2。为了全局验证双精度值,我使用CustomNumberEditor。确实执行了验证。
但是当我输入1234aaa、123aa45 等数字时,我希望NumberFormatException 会被抛出,但事实并非如此。文档说,
ParseException 如果指定字符串的开头不能被 已解析
因此,上面提到的这些值被解析为它们表示为数字,然后省略字符串的其余部分。
为避免这种情况并使其抛出异常,当输入此类值时,我需要通过扩展 PropertyEditorSupport 类来实现我自己的属性编辑器,如本 question 中所述。
package numeric.format;
import java.beans.PropertyEditorSupport;
public final class StrictNumericFormat extends PropertyEditorSupport
{
@Override
public String getAsText()
{
System.out.println("value = "+this.getValue());
return ((Number)this.getValue()).toString();
}
@Override
public void setAsText(String text) throws IllegalArgumentException
{
System.out.println("value = "+text);
super.setValue(Double.parseDouble(text));
}
}
我在带有@InitBinder注解的方法中指定的编辑器如下。
package spring.databinder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public final class GlobalDataBinder
{
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request)
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateFormat.setLenient(false);
binder.setIgnoreInvalidFields(true);
binder.setIgnoreUnknownFields(true);
//binder.setAllowedFields("startDate");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//The following is the CustomNumberEditor
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setGroupingUsed(false);
binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, numberFormat, false));
}
}
由于我使用的是 Spring 3.2,我可以利用 @ControllerAdvice
出于好奇,StrictNumericFormat 类中 PropertyEditorSupport 类中的 覆盖 方法永远不会被调用,并且将输出重定向到控制台的语句在这些方法中指定(@ 987654335@ 和 setAsText()) 不在服务器控制台上打印任何内容。
我已经尝试了question 的所有答案中描述的所有方法,但没有一个对我有用。我在这里想念什么?这是否需要在某些 xml 文件中进行配置?
【问题讨论】:
标签: spring validation spring-mvc property-editor