• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

基于SpringBoot项目遇到的坑–Date入参问题

springboot 搞代码 4年前 (2022-01-09) 27次浏览 已收录 0个评论
文章目录[隐藏]

SpringBoot Date入参问题

springboot项目遇到的坑—–使用@ResponseBody @RequestBody,对象Date 类型入参,返回json格式化

1.传输中的Date类型时间不准确

时区会有8个小时偏差

原因分析

而SpringBoot默认的是Jackson框架转换,而Jackson默认的时间时区是GMT,对于中国时间少8个小时

本文来源gao*daima.com搞@代#码&网6解决方案

在传输的Date属性字段上加此注解

@JsonFormat(timezone = “GMT+8”,pattern = “yyyy-MM-dd”)

在传输实体类中定义一个Long型成员变量存储时间戳 传输过程中只传时间戳 后台将其进行转换为Date然后赋值

   class Test{
		private Date time;
		private Long timeLong;
   }
   
   @PostMapping("/test")
   public Test test(@RequestBody Test test){
       test.setTime(new Date(test.getTimeLone()));
       return test;
   }

2.后台返回的json数据

其中Date类型接收会自动转换成Long类型的时间戳

原因分析:

springboot1.x版本默认的json处理是jackson 会将date字段返回时间戳

解决方案:

全局配置

spring:  
 jackson:
   time-zone: GMT+8
   date-format: yyyy-MM-dd HH:mm:ss

如果个别实体需要使用其他格式的 pattern,在实体上加入注解即可

@JsonFormat(timezone = “GMT+8”,pattern = “yyyy-MM-dd”)
private Date time;

springboot接口入参的一些问题

最近在工作中遇到一个接口入参类型转换错误未被处理的问题,于是整理了一些关于springmvc入参的问题

入参绑定

1、入参中我们最常见的是date类型的参数转换,这个可以通过注解来实现参数类型的转换,只需在bean对象的属性上方添加注解@DateTimeFormat(pattern=“yyyy-MM-dd”),pattern为时间对象的格式化

2、在controller类里定义数据绑定类

/**
     * 在controller层中加入一段数据绑定代码
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) throws Exception{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
    }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:基于SpringBoot项目遇到的坑–Date入参问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址