Spring的自定义参数转换器(将可以转换的类型进行转换)

//可以在controller中定义用于转换的方法

public class DateConverter implements Converter<String, Date> {

/**

 * 转换方法

 */

public Date convert(String source) {

     // 1.定义转换格式对象(2016-02-03 13:22:53)

     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     try {

         // 转换成功直接返回

         return format.parse(source);

     } catch (ParseException e) {

         e.printStackTrace();

     }

     // 转换异常,返回null

     return null;

}

}

二.在springmvc中配置引入转换

<!-- 注解驱动方式配置处理器映射器和处理器适配器 -->

        <mvc:annotation-driven conversion-service="conversionService"/>

        <!-- 配置自定义转换服务 -->

        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

        <property name="converters">

             <set>

                 <bean class="cn.itheima.ssm.converter.DateConverter"/>

             </set>

        </property>

        </bean>

猜你喜欢

转载自www.cnblogs.com/supertan/p/9222176.html