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

岁酱吖の 提交于 2019-12-05 17:51:42
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>
 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!