- 背景:
虽然spring内置多种类型转换器,可以将请求参数自动转换为所需要的目标类型,从而不需要显式转换,但难免遇到无法转换得情况。例如:日期格式转发当请求参数日期格式为非2022/1/6这种格式就无法转换,因此需要自定义格式转换器。
- 格式转化器
例子:
- 创建格式转化器类(日期)——
public class ConverterStringToDate implements Converter<String,Date> {
@Override
public Date convert(String s) {
if (!StringUtils.isEmpty(s)) {
if (s.split("-").length==3) {
DateFormat date = new SimpleDateFormat("yyyy-mm-dd");
try {
return date.parse(s);
} catch (ParseException e) {
throw new RuntimeException("日期格式错误"+s);
}
}else if (s.split("/").length==3) {
DateFormat date = new SimpleDateFormat("yyyy/mm/dd");
try {
return date.parse(s);
} catch (ParseException e) {
throw new RuntimeException("日期格式错误"+s);
}
} else if (s.split(".").length==3) {
DateFormat date = new SimpleDateFormat("yyyy.mm.dd");
try {
return date.parse(s);
} catch (ParseException e) {
throw new RuntimeException("日期格式错误"+s);
}
}
}
return null;
}
}
- 在spring配置文件中进行自定义格式转化器配置——
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
<!-- 配置自定义转换器-->
<bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionServiceFactoryBean">
<property name="converters" >
<set>
<!-- 自定义格式转化器类配置-->
<bean class="dt.until.ConverterStringToDate"></bean>
</set>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" name="viewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>