自定义类型转换器

1、创建自定义类型转换器类

package com.ly.springmvc.converter;

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

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

public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        if(s == null) {
            return null;
        }
        s = s.trim();
        if("".equals(s)) {
            return null;
        }
        String pattern = "yyyy-MM-dd HH:mm:ss";
        if(s.length() == 10) {
            pattern = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("字符串格式非yyyy-MM-dd HH:mm:ss");
        }
    }
}

 

2、在springmvc配置文件中注册自定义类型转换器

    <!--自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.ly.springmvc.converter.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

 

3、在springmvc配置文件中配置自定义类型转换器生效

 

    <!--启SpringMVC的注解驱动模式-->
    <!--conversion-service 配置自定义类型转换器生效-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

4、请求

<form action="param/test1" method="post">
    userName:<input type="text" name="userName"><br>
    age:<input type="text" name="age"><br>
    birthday:<input type="text" name="birthday"><br>
    <input type="submit" name="提交">
</form>

5、处理方法

    @RequestMapping("/param/test1")
    public String testParam6(User u) {
        System.out.println("testParam6");
        System.out.println(u);
        return "success";
    }

6、总结

6.1、springmvc中String类型转为Date类型默认的格式是年月日之间用/分隔

posted @ 2020-02-26 20:52  牛牛的自留地  阅读(219)  评论(0编辑  收藏  举报