springmvc中如何自定义类型转换器

package com.hope.utils;


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;

/**
第一步定义一个类型转换器的类
* @author newcityman
* @date 2019/11/26 - 19:57
*/
public class StringToDateConverter implements Converter<String,Date>{

/**
*
* @param source
* @return
*/
@Override
public Date convert(String source) {
if(StringUtils.isEmpty(source)){
throw new RuntimeException("参数不能为空,请输入一个参数。");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(source);
} catch (ParseException e) {
throw new RuntimeException("日期转换失败,请联系管理员。");
}
}
}

// 第二步,在springmvc.xml中配置自定义类型转换器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--指定spring扫描的包-->
<context:component-scan base-package="com.hope"></context:component-scan>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.hope.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>

<!--开启springmvc框架注解的支持,包含开启处理器映射器和处理器适配器-->
<mvc:annotation-driven conversion-service="conversionService"/>
</beans>
 

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11938550.html