在SpringMVC中bean中定义了日期,双等类型,如果没有做任何处理的话,日期以及双都无法绑定。
解决的办法就是使用spring mvc提供的@InitBinder标签
在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个控制器中。剩下的控制器都继承该类.spring自己提供了大量的实现类,诸如CustomDateEditor, CustomBooleanEditor, CustomNumberEditor等许多,基本上够用。
当然,我们也可以不使用他自己自带这些编辑器类,那下面我们自己去构造几个
进口org.springframework.beans.propertyeditors.PropertiesEditor; 公开课DoubleEditor延伸PropertiesEditor { @Override 公共空间setAsText(字符串文本)抛出IllegalArgumentException { 如果(文本==null | | text.equals (" ")) { 文本=" 0 "; } setValue (Double.parseDouble(文本)); } @Override 公共字符串getAsText () { getValue()返回.toString (); } }
进口org.springframework.beans.propertyeditors.PropertiesEditor; 公开课IntegerEditor延伸PropertiesEditor { @Override 公共空间setAsText(字符串文本)抛出IllegalArgumentException { 如果(文本==null | | text.equals (" ")) { 文本=" 0 "; } setValue (Integer.parseInt(文本)); } @Override 公共字符串getAsText () { getValue()返回.toString (); } } >之前进口org.springframework.beans.propertyeditors.PropertiesEditor; 公开课FloatEditor延伸PropertiesEditor { @Override 公共空间setAsText(字符串文本)抛出IllegalArgumentException { 如果(文本==null | | text.equals (" ")) { 文本=" 0 "; } setValue (Float.parseFloat(文本)); } @Override 公共字符串getAsText () { getValue()返回.toString (); } }进口org.springframework.beans.propertyeditors.PropertiesEditor; 公开课LongEditor延伸PropertiesEditor { @Override 公共空间setAsText(字符串文本)抛出IllegalArgumentException { 如果(文本==null | | text.equals (" ")) { 文本=" 0 "; } setValue (Long.parseLong(文本)); } @Override 公共字符串getAsText () { getValue()返回.toString (); } }在BaseController中
@InitBinder 保护无效initBinder (WebDataBinder粘合剂){ binder.registerCustomEditor(日期。类,新CustomDateEditor(新SimpleDateFormat (yyyy-MM-dd HH: mm: ss),真的));/binder.registerCustomEditor (int。类,新CustomNumberEditor (int。类,true)); binder.registerCustomEditor (int。类,新IntegerEditor ());/binder.registerCustomEditor(长。类,新CustomNumberEditor(长。类,true)); binder.registerCustomEditor(长。类,新LongEditor ()); binder.registerCustomEditor(双。类,新DoubleEditor ()); binder.registerCustomEditor(浮动。类,新FloatEditor ()); }代码如下:
公共类org.springframework.beans.propertyeditors。PropertiesEditor java.beans延伸。PropertyEditorSupport {,
看到没?如果你的编辑器类直接继承PropertyEditorSupport也可以。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
spring mvc使用@InitBinder标签对表单数据绑定的方法