SpringMVC配置任何类型转换器 Converter
(以时间类型为例)
从页面传到后台的时间字符串转成日期格式封装到实体类
1. 定义时间DateConverter转换类实现 Converter<String, Date> 接口
package com.igeek.ssm.controller;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.core.convert.converter.Converter;/*** * TODO** 10月24日下午7:57:37*/public class DateConverter implements Converter<String, Date> {@Overridepublic Date convert(String dateStr) {Date date = null;SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {date = dateFormat.parse(dateStr);} catch (ParseException e) {//e.printStackTrace();dateFormat = new SimpleDateFormat("yyyy-MM-dd");try {date = dateFormat.parse(dateStr);} catch (ParseException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}return date;}}
2. springmvc.xml ;可以配多组
<!-- 配置配置类型转换器注解驱动 --><mvc:annotation-driven conversion-service="conversionService" /><!-- 配置类型转换器 --><bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="converters"><set><bean class="com.igeek.ssm.controller.DateConverter" /></set></property></bean>
3.页面 ;自动把时间字符串按格式转成时间类型传往后台