这篇文章主要介绍了SpringMVC自定义类型转换器实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
页面录入的字符串:2019/12/05可以映射到实体的日期属性上,但是如果是录入2019-12-05就会报错400 bad request,想要以2019-12-05日期格式的方式映射到实体的日期属性上,需要自定义类型转换器,主要步骤如下:
1、 自定义类实现Convertro<S,T>接口
2、Springmvc.xml中配置ConversionServiceFactoryBean,其属性上配置我们自定义的转换器
3、欲使配置的转换器生效,需要将springmvc.xml的<mvc:annotation-driven />改为
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
1、 自定义类实现Convertro<S,T>接口
package com.example.util;import org.springframework.core.convert.converter.Converter;import org.springframework.util.StringUtils;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class StingToDateConvertr implements Converter<String, Date> { @Override public Date convert(String s) { if(StringUtils.isEmpty(s)){ throw new RuntimeException("日期字符串不能为空!"); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { return df.parse(s); } catch (ParseException e) { throw new RuntimeException("类型转换出错!"); } }}2、Springmvc.xml中配置ConversionServiceFactoryBean,其属性上配置我们自定义的转换器
<!--配置自定义类型转换器--><bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.example.util.StingToDateConvertr" /> </set> </property></bean>3、欲使配置的转换器生效,需要将springmvc.xml的<mvc:annotation-driven />改为
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
springmvc.xml的完整配置如下:
注意:自定义的类型转换器生效之后,日期格式就只能使用yyyy-MM-dd的格式了,若再使用原有的yyyy/MM/dd格式就会报错!
如有理解不到之处,望指正!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。