Time transformation class type parameter

Time transformation class type parameter

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 完成 字符串转换为date 日期格式
 */
public class DateUtils implements Converter<String, Date> {
    @Override
    //完成格式转换
    public Date convert(String source) {
        if(StringUtils.isEmpty(source)){
            throw new RuntimeException("当前日期不能为空");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(source);//转换成功直接返回一个date对象
        } catch (ParseException e) {
            throw new RuntimeException("日期转换失败");
        }
    }
}

After writing, you can not run.
In the configuration file springMvc.xml

 <!--配置类型转换-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!--converters是工厂bean中必须要配置的一个set集合,集合中包含自定义转换类-->
        <property name="converters">
            <set>
                <!--引入自定义转换器的bean对象-->
                <bean class="com.hp.springmvc.utils.DateUtils"></bean>
            </set>
        </property>
    </bean>

After reference annotation-driven: in mvc

<mvc:annotation-driven conversion-service="conversionService"/>
Published 68 original articles · won praise 7 · views 2524

Guess you like

Origin blog.csdn.net/Cui6023056/article/details/104479341