springboot处理date参数

前言
最近在后台开发中遇到了时间参数的坑,就单独把这个问题提出来找时间整理了一下;
正文
测试方法
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";
}
}
接收参数的几种方式(实验)
- 通过bean来接收数据(表单方式)
- 这种方式只支持"yyyy/MM/dd HH:mm:ss"这种格式的time参数
- 通过bean来接收数据(json格式)
- 这种方式只支持"yyyy-MM-dd HH:mm:ss"这种格式的time参数
- 通过RequestParam注解
- 这种方式只支持"yyyy/MM/dd HH:mm:ss"这种格式的time参数
- 不通过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参数的更多相关文章
- SpringBoot注解验证参数
SpringBoot注解验证参数 废话不多说,直接上表格说明: 注解 作用类型 解释 @NotNull 任何类型 属性不能为null @NotEmpty 集合 集合不能为null,且size大于0 @ ...
- SpringBoot 如何进行参数校验,老鸟们都这么玩的!
大家好,我是飘渺. 前几天写了一篇 SpringBoot如何统一后端返回格式?老鸟们都是这样玩的! 阅读效果还不错,而且被很多号主都转载过,今天我们继续第二篇,来聊聊在SprinBoot中如何集成参数 ...
- SpringBoot 如何进行参数校验
为什么需要参数校验 在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数进行校验,例如登录的时候需要校验用户名和密码是否为空,添加用户的时候校验用户邮箱地址.手机号码格式是否正确. ...
- date 参数(option)-d
记录这篇博客的原因是:鸟哥的linux教程中,关于date命令的部分缺少-d这个参数的介绍,并且12章中的shell编写部分有用到-d参数 date 参数(option)-d与--date=" ...
- SpringBoot接收前端参数的三种方法
都是以前的笔记了,有时间就整理出来了,SpringBoot接收前端参数的三种方法,首先第一种代码: @RestController public class ControllerTest { //访问 ...
- springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743
https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...
- SpringBoot返回date日期格式化
SpringBoot返回date日期格式化,解决返回为TIMESTAMP时间戳格式或8小时时间差 问题描述 在Spring Boot项目中,使用@RestController注解,返回的java对象中 ...
- springboot 获取控制器参数的几种方式
这里介绍springboot 获取控制器参数有四种方式 1.无注解下获取参数 2.使用@RequestParam获取参数 3.传递数组 4.通过URL传递参数 无注解下获取参数无注解下获取参数,需要控 ...
- SpringBoot Controller接收参数的几种方式盘点
本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:SpringBoot Controller接收参数的几种方式盘点: SpringBoot Controller接收参数的几种常用方式盘点 ...
随机推荐
- Node.js返回JSON
在使用JQuery的Ajax从服务器请求数据或者向服务器发送数据时常常会遇到跨域无法请求的错误,常用的解决办法就是在Ajax中使用JSONP.基于安全性考虑,浏览器会存在同源策略,然而<scri ...
- Delphi编译/链接过程
下面展示了Delphi是怎样编译源文件,并且把它们链接起来,最终形成可执行文件. 当Delphi编译项目(Project)时,将编译项目源文件.窗体单元和其他相关单元,在这个过程中将会发生好几件事情: ...
- 移动前端viewPort的那些事
1.viewport简单说 一般来说,移动上的viewport都是大于浏览器窗口的,不同的设备有自己默认的viewport值(980px或1024px). 2.三个viewport的理解(layout ...
- 安装Python,输入pip命令报错———pip Fatal error in launcher: Unable to create process using
今天把Python的安装位置也从C盘剪切到了D盘, 然后修改了Path环境变量中对应的盘符:D:\Python27\;D:\Python27\Scripts; 不管是在哪个目录,Python可以执行了 ...
- django logger转载
https://www.cnblogs.com/jiangchunsheng/p/8986452.html https://www.cnblogs.com/jeavy/p/10926197.html ...
- Streaming Systems笔记
一直心心念的<Streaming Systems>终于有了影印版本,京东110块钱果断买了,很惊喜还是彩印版本. 挖个坑,书看完后写一篇关于流式处理总结的笔记,大体翻看了一遍,总体来说流式 ...
- 开放API接口安全处理!
目录 概念 加密 MD5 Token 开放api参数 重复提交,恶意调用 日志 验证码 开放API接口安全处理! 参考文献: 公钥,私钥和数字签名这样最好理解 (转载) 概念 存在问题: 数据窃取 数 ...
- php提示Undefined index的解决方法
我们在做php开发时有时可能会提示Notice: Undefined index: *** on line 249,出现上面这些是 PHP 的提示而非报错,PHP 本身不需要事先声明变量即可直接使用, ...
- acwing 算法面试、笔试题公开课整理记录
week1 Google KickStart 2019 A轮 讲解视频地址AcWing 549. 训练 tag: 排序 遍历 在线练习地址AcWing 550. 包裹 在线练习地址Ac ...
- bzoj2187 fraction&&hdu3637 Find a Fraction——类欧几里得
bzoj2187 多组询问,每次给出 $a, b, c, d$,求满足 $\frac{a}{b} < \frac{p}{q} < \frac{c}{d}$ 的所有二元组 $(p, q)$ ...