解决问题:java中 只支持2020/2/2这种格式转化成date类型,不能支持2020-2-2这种,通过自定义类型转化器来解决这个问题;
拓展:也可以让Srting转换成javabean
1.编写类继承Converter<>(org.springframework.core.convert.converter.Converter),实现convert()方法
package converter; import java.sql.Date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import javax.management.RuntimeErrorException; import javax.xml.crypto.Data; import org.springframework.context.support.ConversionServiceFactoryBean; import org.springframework.core.convert.converter.Converter; public class date_converter implements Converter<String, java.util.Date> { @Override public java.util.Date convert(String arg0) { if (arg0 == null) { throw new RuntimeException("空值"); } DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd"); try { return dFormat.parse(arg0); } catch (ParseException e) { throw new RuntimeException("错误"); } } }
2.在springmvc中配置
<mvc:annotation-driven conversion-service="ConversionServiceFactoryBean"></mvc:annotation-driven> <!-- 配置类型转换器 --> <bean id="ConversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="converter.date_converter"></bean> </set> </property> </bean>