栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot自定义日期参数转换器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot自定义日期参数转换器

一般不添加任何配置的情况下,后台接收Date类型的字段会出现如下异常:

Failed to convert from type [java.lang.String] to type [java.util.Date] for value

常见解决方案可以在接收实体类的Date参数上添加注解

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime date;

然而如果在每个生成的实体类中,给每一个带有Date类型接收的参数上添加如上注解,感觉又不太节能。

因此我们自定义一个日期参数转换器让他自动转换,分为俩步。

第一步
import org.springframework.core.convert.converter.Converter;

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



public class DateConverter implements Converter {
    private final SimpleDateFormat smf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Date convert(String s) {
        if ("".equals(s) || null == s) {
            return null;
        }

        try {
            return smf.parse(s);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
第二步
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }
}
写个简单的接口测试一下
    @GetMapping("/getDate")
    public Date getDate(Date date) {
        return date;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/632453.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号