Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2018-06-19'

解决方案:

1、局部转换

  1.  //只需要加上下面这段即可,注意不能忘记注解  
  2.     @InitBinder  
  3.     public void initBinder(WebDataBinder binder, WebRequest request) {  
  4.           
  5.         //转换日期  
  6.         DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  7.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器  
  8.     }  

2、全局转换

    创建CustomDate类实现WebBindingInitializer

  1. import java.text.DateFormat;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Date;  
  4. import org.springframework.beans.propertyeditors.CustomDateEditor;  
  5. import org.springframework.web.bind.WebDataBinder;  
  6. import org.springframework.web.bind.support.WebBindingInitializer;  
  7. import org.springframework.web.context.request.WebRequest;  
  8.   
  9. /** 
  10.  * @作者:JackHisen(GWD) 
  11.  * @项目名:shoppingmall 
  12.  * @时间:2017-7-12 下午10:39:10 
  13.  * @version 1.0 
  14.  */  
  15. public class CustomDate implements WebBindingInitializer{  
  16.   
  17.     @Override  
  18.     public void initBinder(WebDataBinder binder, WebRequest request) {  
  19.         // TODO Auto-generated method stub  
  20.         //转换日期  
  21.         DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  22.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, true));  
  23.     }  
  24. }  

在Spring-MVC.xml中配置日期转换

  1.  <!-- 日期转换 -->  
  2.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  3.         <property name="webBindingInitializer">  
  4.             <bean class="com.gwd.shopping.core.web.CustomDate"/>  
  5.         </property>  
  6.     </bean>  

猜你喜欢

转载自blog.csdn.net/ss77585210/article/details/80726764