在开发当中经常遇到过这种情况,Controller方法中接收参数的是Integer,或Double类型时,客户端经常会传字符串null或(null),这时服务器就会抛出异常。
本来是前端不小心导致的问题,我们可不想背锅。
想直接执行方法,如下:
public class MyWebBindingInitializer extends ConfigurableWebBindingInitializer {
@Override
public void initBinder(WebDataBinder binder, WebRequest request) {
super.initBinder(binder, request);
binder.registerCustomEditor(Number.class, new MyCustomNumberEditor(Number.class, true));
}
}
下面这段代码是我重写springframework中CustomNumberEditor类,在关键方法增加是否是数字的验证。
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.text.NumberFormat;
public class MyCustomNumberEditor extends PropertyEditorSupport {
private final Class<? extends Number> numberClass;
private final NumberFormat numberFormat;
private final boolean allowEmpty;
public MyCustomNumberEditor(Class<? extends Number> numberClass, boolean allowEmpty) throws IllegalArgumentException {
this(numberClass, (NumberFormat) null, allowEmpty);
}
public MyCustomNumberEditor(Class<? extends Number> numberClass, NumberFormat numberFormat, boolean allowEmpty) throws IllegalArgumentException {
if (numberClass != null && Number.class.isAssignableFrom(numberClass)) {
this.numberClass = numberClass;
this.numberFormat = numberFormat;
this.allowEmpty = allowEmpty;
} else {
throw new IllegalArgumentException("Property class must be a subclass of Number");
}
}
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
this.setValue((Object) null);
} else if (!org.apache.commons.lang3.math.NumberUtils.isNumber(text)) {
this.setValue((Object) null);//如果不是数字类型
} else if (this.numberFormat != null) {
this.setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
} else {
this.setValue(NumberUtils.parseNumber(text, this.numberClass));
}
}
public void setValue(Object value) {
if (value instanceof Number) {
super.setValue(NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass));
} else {
super.setValue(value);
}
}
public String getAsText() {
Object value = this.getValue();
if (value == null) {
return "";
} else {
return this.numberFormat != null ? this.numberFormat.format(value) : value.toString();
}
}
}
配置文件:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.ssb.web.common.MyWebBindingInitializer">
<property name="conversionService" ref="conversionService"/>
</bean>
</property>
...
</bean>