一、建立自定義類型轉換器類java
package com.ly.springmvc.converter; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateConverter implements Converter<String, Date> { @Override public Date convert(String s) { if(s == null) { return null; } s = s.trim(); if("".equals(s)) { return null; } String pattern = "yyyy-MM-dd HH:mm:ss"; if(s.length() == 10) { pattern = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("字符串格式非yyyy-MM-dd HH:mm:ss"); } } }
二、在springmvc配置文件中註冊自定義類型轉換器spring
<!--自定義類型轉換器--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.ly.springmvc.converter.StringToDateConverter"></bean> </set> </property> </bean>
三、在springmvc配置文件中配置自定義類型轉換器生效mvc
<!--啓SpringMVC的註解驅動模式--> <!--conversion-service 配置自定義類型轉換器生效--> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
四、請求app
<form action="param/test1" method="post"> userName:<input type="text" name="userName"><br> age:<input type="text" name="age"><br> birthday:<input type="text" name="birthday"><br> <input type="submit" name="提交"> </form>
五、處理方法ide
@RequestMapping("/param/test1") public String testParam6(User u) { System.out.println("testParam6"); System.out.println(u); return "success"; }
六、總結post
6.一、springmvc中String類型轉爲Date類型默認的格式是年月日之間用/分隔spa