前言

最近在后台开发中遇到了时间参数的坑,就单独把这个问题提出来找时间整理了一下;

正文

测试方法

bean代码:


public class DateModelNoAnnotation {
private Integer id;
private Date receiveDate;
}

controller代码:


@RestController
@RequestMapping("/date")
public class DateVerifyController {
// 方式一
@PostMapping("/no")
public String dateUnNoAnnotation(DateModelNoAnnotation dateModelNoAnnotation){
System.out.println(dateModelNoAnnotation.toString());
return "SUCCESS";
} // 方式二
@PostMapping("/has")
public String dateHasAnnotation(@RequestBody DateModelNoAnnotation dateModelNoAnnotation){
System.out.println(dateModelNoAnnotation.toString());
return "SUCCESS";
}
// 方式三
@GetMapping("/param")
public String dateParams(@RequestParam("id")Integer id, @RequestParam("receiveDate")Date receiveDate){
System.out.println("id====="+id);
System.out.println("receiveDate====="+receiveDate);
System.out.println("receiveDate====="+receiveDate.getTime());
return "SUCCESS";
}
// 方式四
@GetMapping("/no/param")
public String dateNoParams(Integer id,Date receiveDate){
System.out.println("id====="+id);
System.out.println("receiveDate====="+receiveDate);
System.out.println("receiveDate====="+receiveDate.getTime());
return "SUCCESS";
}
}

接收参数的几种方式(实验)

  1. 通过bean来接收数据(表单方式)
  • 这种方式只支持"yyyy/MM/dd HH:mm:ss"这种格式的time参数
  1. 通过bean来接收数据(json格式)
  • 这种方式只支持"yyyy-MM-dd HH:mm:ss"这种格式的time参数
  1. 通过RequestParam注解
  • 这种方式只支持"yyyy/MM/dd HH:mm:ss"这种格式的time参数
  1. 不通过RequestParam注解
  • 这种方式只支持"yyyy/MM/dd HH:mm:ss"这种格式的time参数

以上几种接收参数的方式接收的参数格式并不统一,而且有时候web前端传入的时间参数为时间戳,还得写修改接口或者让其自己修改格式;

后端给前端统一返回json格式的数据,且时间格式为"yyyy-MM-dd HH:mm:ss"

解决方案

开发之前统一时间接口接收的时间格式

一 yyyy/MM/dd HH:mm:ss 格式

后端所有接口统一接收"yyyy/MM/dd HH:mm:ss"或"yyyy/MM/dd"格式时间参数

第一种: 舍弃上边的方式二的接口

第二种:不舍弃方拾二,在bean的时间属性上添加JsonFormat注解,例如:


com.fasterxml.jackson.annotation.JsonFormat; @JsonFormat(timezone = "GMT+8",pattern = "yyyy/MM/dd HH:mm:ss")
private Date receiveDate;

优势: 不舍弃方式二接口,且统一了时间格式

使用该注解的弊端: 当pattern="yyyy/MM/dd" 时, 只支持处理“2019/09/03"格式时间参数,不支持“2019/09/03 00:00:00”,且会报错,当pattern="yyyy/MM/dd HH:mm:ss"时,只支持处理“2019/09/03 00:00:00"格式时间参数,其余格式均会报错;

二 接收所有时间格式

  • yyyy-MM-dd HH:mm:ss 格式
  • yyyy-MM-dd 格式
  • 时间戳
  • yyyy/MM/dd HH:mm:ss 格式
  • yyyy/MM/dd 格式
注意

该方式不对json或xml的数据处理,比如使用@RequestBody注解的bean(也就是方式二)

工具类:


import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author gyc
* @title: DateConverter
* @projectName app
* @date 2019/8/1914:36
* @description: 时间转换类
*/
public class CourseDateConverter implements Converter<String, Date> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String dateFormata = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
private static final String shortDateFormata = "yyyy/MM/dd";
private static final String timeStampFormat = "^\\d+$";
@Override
public Date convert(String value) {
if(StringUtils.isEmpty(value)) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
SimpleDateFormat formatter;
if (value.contains(":")) {
//yyyy-MM-dd HH:mm:ss 格式
formatter = new SimpleDateFormat(dateFormat);
} else {
//yyyy-MM-dd 格式
formatter = new SimpleDateFormat(shortDateFormat);
}
return formatter.parse(value);
} else if (value.matches(timeStampFormat)) {
//时间戳
Long lDate = new Long(value);
return new Date(lDate);
}else if (value.contains("/")){
SimpleDateFormat formatter;
if (value.contains(":")) {
// yyyy/MM/dd HH:mm:ss 格式
formatter = new SimpleDateFormat(dateFormata);
} else {
// yyyy/MM/dd 格式
formatter = new SimpleDateFormat(shortDateFormata);
}
return formatter.parse(value);
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
}
将时间转换类应用到接口上

介绍两种方式:使用@Component + @PostConstruct或@ControllerAdvice + @InitBinder

第一种方式:

@Component + @PostConstruct

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct; @Component
public class WebConfigBeans {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@PostConstruct
public void initEditableAvlidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
if(initializer.getConversionService()!=null) {
GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService(); genericConversionService.addConverter(new DateConverterConfig()); }
}
}

第二种方式:

@ControllerAdvice + @InitBinder

import com.aegis.config.converter.DateConverter;
import com.aegis.model.bean.common.JsonResult;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
public class CourseControllerHandler {
@InitBinder
public void initBinder(WebDataBinder binder) {
GenericConversionService genericConversionService = (GenericConversionService) binder.getConversionService();
if (genericConversionService != null) {
genericConversionService.addConverter(new CourseDateConverter());
}
}
}
最后

我使用的最后的一种方法的第二种方式

总结

时间参数这个坑还是有点大的,之前都是针对性的处理,只要一变化就没法了;现在这个还是可以应付基本上会出现的错误了;

springboot处理date参数的更多相关文章

  1. SpringBoot注解验证参数

    SpringBoot注解验证参数 废话不多说,直接上表格说明: 注解 作用类型 解释 @NotNull 任何类型 属性不能为null @NotEmpty 集合 集合不能为null,且size大于0 @ ...

  2. SpringBoot 如何进行参数校验,老鸟们都这么玩的!

    大家好,我是飘渺. 前几天写了一篇 SpringBoot如何统一后端返回格式?老鸟们都是这样玩的! 阅读效果还不错,而且被很多号主都转载过,今天我们继续第二篇,来聊聊在SprinBoot中如何集成参数 ...

  3. SpringBoot 如何进行参数校验

    为什么需要参数校验 在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数进行校验,例如登录的时候需要校验用户名和密码是否为空,添加用户的时候校验用户邮箱地址.手机号码格式是否正确. ...

  4. date 参数(option)-d

    记录这篇博客的原因是:鸟哥的linux教程中,关于date命令的部分缺少-d这个参数的介绍,并且12章中的shell编写部分有用到-d参数 date 参数(option)-d与--date=" ...

  5. SpringBoot接收前端参数的三种方法

    都是以前的笔记了,有时间就整理出来了,SpringBoot接收前端参数的三种方法,首先第一种代码: @RestController public class ControllerTest { //访问 ...

  6. springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743

    https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...

  7. SpringBoot返回date日期格式化

    SpringBoot返回date日期格式化,解决返回为TIMESTAMP时间戳格式或8小时时间差 问题描述 在Spring Boot项目中,使用@RestController注解,返回的java对象中 ...

  8. springboot 获取控制器参数的几种方式

    这里介绍springboot 获取控制器参数有四种方式 1.无注解下获取参数 2.使用@RequestParam获取参数 3.传递数组 4.通过URL传递参数 无注解下获取参数无注解下获取参数,需要控 ...

  9. SpringBoot Controller接收参数的几种方式盘点

    本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:SpringBoot Controller接收参数的几种方式盘点: SpringBoot Controller接收参数的几种常用方式盘点 ...

随机推荐

  1. 正则表达式,匹配非本站图片网址去掉img标签内容实例

    正则表达式,匹配非本站图片网址去掉img标签内容实例 在线正则表达式测试http://tool.oschina.net/regex/# 测试内容: <div><p>eee< ...

  2. Django模板系统:Template

    一.模板常用语法 1.1 变量 符号:{{ }} 表示变量,在模板渲染的时候替换成值 使用方式:{{ 变量名 }}:变量名由字母数字和下划线组成 点(.)在模板语言中有特殊的含义,用来获取对象的相应属 ...

  3. 自定义组件实现双向绑定v-model

    自定义组件实现 v-model 双向绑定,首先要先明白 v-model,这个指令到底实现了什么? v-model实际做的事情就是:传入一个value属性值,然后监听input事件返回一个值,用该返回值 ...

  4. 5 LInux系统目录结构

      ls /    显示根目录下的文件 /bin bin是Binary的缩写,这个目录存放着经常使用的命令 /boot 存放的是启动Linux时使用的一些核心文件,包括一些连接文件以及镜像文件 /de ...

  5. Excel单元格锁定及解锁

    Excel VBA 宏 学习使用: 一.工作表单元格的锁定: 1.选择需要锁定的单元格. 2.鼠标右键----设置单元格格式. 3.设置  “保护”--锁定 -- 确定. 4.回到表头,[审阅]--- ...

  6. socket套接字及粘包问题

    socket套接字 1.什么是socket socket是一个模块,又称套接字,用来封装互联网协议(应用层以下的层) 2.为什么要有socket 实现应用层以下的层的工作,提高开发效率 3.怎么使用s ...

  7. $.fn与$.fx什么意思; $.extend与$.fn.extend用法区别; $(function(){})和(function(){})(jQuery)

    $.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效. 如扩展$.fn.abc() 那么你可以这样子:$("#div").abc(); 通常使 ...

  8. [KCOJ20170214]又一个背包

    题目描述 Description 小W要去军训了!由于军训基地是封闭的,小W在军训期间将无法离开军训基地.所以他没有办法出去买他最爱吃的零食.万般无奈的小W只好事先买好他爱吃的零食,装在背包里带入军训 ...

  9. piral 基于typescript 的微前端开发框架

    piral有一个微前端开发框架,功能强大,文档比较全,扩展能力也比较好 包含以下特性: 特性 高度模块化 多框架兼容 支持资源文件的拆分 全局状态管理 独立开发和部署 CLI工具 与同类框架的比较 参 ...

  10. ESA2GJK1DH1K基础篇: Android连接MQTT简单的Demo

    题外话 我老爸也问我物联网发展的趋势是什么!!!!!! 我自己感觉的:(正在朝着 "我,机器人" 这部电影的服务器方向发展) 以后的设备都会和服务器交互,就是说本地不再做处理,全部 ...