5、日期类型转换问题

SpringMVC在参数绑定之前将请求中携带的参数转换成各种数据类型并通过反射给参数赋值
但是在一些情况下SpringMVC无法将一些字符串转换成我们想要的数据类型,如下例子:

SpringMVC默认支持以斜杠为分隔符的字符串转换成Date类型的数据

如果改字符串的分隔符是其他的,SpringMvc默认无法将该字符串转换成Date数据类型

1、使用@DateTimeFormat注解

该注解可以用在参数上或实体类的属性上

(1)写在参数上
该种写法可读性强,但是无法实现参数绑定实体类对象

/**
 * @DateTimeFormat(pattern=支持转换的日期格式)将字符串的日期格式转换成Date类型,并赋值
 * 此时,该日期类型就不再支持默认的以斜杠为分隔符的日期类型转换
 */
@RequestMapping("/selectUser")
public String selectUser2(@DateTimeFormat(pattern="yyyy-MM-dd")Date birthday, String username, Integer age){
    System.out.println(birthday + username + age);
    return "success";
}

(2)写在实体类的属性上
这种写法,可以实现参数绑定实体类对象

public class User {
    //基本数据类型
    private String username;
    private Integer age;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birthday;

Controller

@RequestMapping("/selectUser")
public String selectUser2(User user){
    System.out.println(user.toString());
    return "success";
}

这两种写法都是针对于某个方法或某个类的属性进行日期格式转换,并不是全局性的

2、自定义日期转换器

第一步 创建一个类,并实现Converter接口

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 将日期转换成字符串
 */
public class String2Date implements Converter<String, Date> {
    @Override
    public Date convert(String s) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date d = null;
        try {
            d = sdf.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("数据类型转换出现异常");
        }
        return d;
    }
}

在spring的配置文件中配置,该配置为全局配置

<!--配置自定义类型转换器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <!--注册Date类型转换器-->
            <bean class="com.example.utils.String2Date"></bean>
        </set>
    </property>
</bean>

<!--开启SpringMVC框架注解的支持-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
posted @ 2020-07-31 17:13  lawrence林  阅读(197)  评论(0编辑  收藏  举报