在SpringMVC中,bean中定義了Date,double等類型,如果沒有做任何處理的話,日期以及double都無法綁定。
解決的辦法就是使用spring mvc提供的@InitBinder標(biāo)簽
在我的項(xiàng)目中是在BaseController中增加方法initBinder,并使用注解@InitBinder標(biāo)注,那么spring mvc在綁定表單之前,都會(huì)先注冊(cè)這些編輯器,當(dāng)然你如果不嫌麻煩,你也可以單獨(dú)的寫在你的每一個(gè)controller中。剩下的控制器都繼承該類。spring自己提供了大量的實(shí)現(xiàn)類,諸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等許多,基本上夠用。
當(dāng)然,我們也可以不使用他自己自帶這些編輯器類,那下面我們自己去構(gòu)造幾個(gè)
import org.springframework.beans.propertyeditors.PropertiesEditor; public class DoubleEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Double.parseDouble(text)); } @Override public String getAsText() { return getValue().toString(); } }