关于Spring MVC对非String类型进行校验时的出错处理
我在对User.age (Integer型),进行校验时,如果
输入 的是字符总是出错:
Failed to convert property value of type [
Java .lang.String] to required type [java.lang.Integer] for property age; nested exception is java.lang.NumberFormatException: For input string: "ff"
解决方法:
1.本例用的是commons-validator的开源框架
2.在Controller中加
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
binder.registerCustomEditor(Integer.class, null,new CustomNumberEditor(Integer.class, null, true));
binder.registerCustomEditor(Long.class, null,new CustomNumberEditor(Long.class, null, true));
binder.registerCustomEditor(byte[].class,new ByteArrayMultipartFileEditor());
SimpleDateFormat dateFormat = new SimpleDateFormat(getText("date.format", request.getLocale()));
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, null,new CustomDateEditor(dateFormat, true));
}
3.在资源文件ApplicationResources_zh_CN.properties 中加:
user.age=\u5e74\u9f84
typeMismatch.java.lang.Integer={0} \u5fc5\u987b\u4e3a\u4e00\u6570\u503c\u3002
4.一些朋友说在用非对象类型如int时也总是出错,但我在测试时发现不管是用int 还是用float,如果不输或输入字符,系统均会自动赋值 int为0,float为0.0
5.以下是一个不错的入门 文章,转发于” jamyy2000 的专栏”:
关于Spring中Commons Validator的使用说明
复制本页网址和标题,发送给你QQ/Msn的好友一起分享
上一篇:EJB3.0学习之运行环境配置
下一篇:Spring MVC验证的配置步骤