当前位置: 首页 > news >正文

Get请求-LocalDateTime的转换问题

问题分析

        在处理 HTTP GET 请求时,如果尝试接收一个 LocalDateTime 类型的参数,可能会遇到序列化或反序列化的问题。这是因为 URL 参数通常是字符串形式,而 LocalDateTime 是 Java 中的一个日期时间对象,需要适当的格式化才能正确解析。不然可以会出现如下错误:

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value '2024-08-08 22:22:22'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2024-08-08 22:22:22]

解决方案

一、LocalDateTime 转换器(全局)

        get请求的话, 不走反序列化,而是直接将String的值塞给对应的类型,默认是没有转换器,会抛出异常。

        配置了转换器后,当用LocalDateTime接收get请求参数的时候,就会进入这个转换器中。


import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;@Component
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");@Overridepublic LocalDateTime convert(String source) {return LocalDateTime.parse(source, formatter);}
}

二、显示参数处理

        如果不想使用自定义转换器,可以在控制器方法中显式地处理字符串参数,并手动转换为 LocalDateTime:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;@RestController
public class MyController {@GetMapping("/test1")public void resolveRequestParamDateTime(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime localDateTime) {log.info("localDateTime:{}", localDateTime);}private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");@GetMapping("/test2")public String getDateTime(@RequestParam("date") String dateString) {LocalDateTime date = LocalDateTime.parse(dateString, formatter);// 处理逻辑return "Received date: " + date;}
}

三、application.yml配置

        application.yml配置 SpringBoot2.3.x以及更高的版本,springmvc增加了日期时间格式配置,既可以解决LocalDateTime类型参数解析,也可以解决Date类型参数解析

spring:mvc:date: yyyy-MM-ddtime: HH:mm:ssdate-time: yyyy-MM-dd HH:mm:ss

四、LocalDateTimeConfig

        在Spring IOC容器中注入Converter,SpringBoot会自动将IOC容器中的Converter放到GenericConversionService中


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;@Configuration
public class LocalDateTimeConfig {@Beanpublic Converter<String, LocalDateTime> stringToLocalDateTimeConverter() {return new Converter<String, LocalDateTime>() {@Overridepublic LocalDateTime convert(String source) {return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));}};}@Beanpublic Converter<String, LocalDate> stringToLocalDateConverter() {return new Converter<String, LocalDate>() {@Overridepublic LocalDate convert(String source) {return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));}};}@Beanpublic Converter<String, LocalTime> stringToLocalTimeConverter() {return new Converter<String, LocalTime>() {@Overridepublic LocalTime convert(String source) {return LocalTime.parse(source, DateTimeFormatter.ofPattern("HH:mm:ss"));}};}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Python在数据科学与机器学习中的应用
  • 大话Python|基础语法(上)
  • 【监控】【Nginx】使用 Docker 部署 ELK Stack 监控 Nginx
  • Vite + Vue + TypeScript 项目搭建总结
  • 【ComfyUI】自定义节点ComfyUI_LayerStyle——模仿 Adob​​e Photoshop 的图层样式、图层混合、图文混合、添加不可见水印
  • 安卓13去掉下拉菜单的Dump SysUI 堆的选项 android13删除Dump SysUI 堆
  • C语言中数组和字符串的联系
  • OpenAI 刚刚推出 o1 大模型!!突破LLM极限
  • Ruby-SAML CVE-2024-45409 漏洞解决方案
  • 7.搭建个人金融数据库之快速获取股票列表和基本信息!
  • OpenHarmony(鸿蒙南向开发)——小型系统芯片移植指南(二)
  • 深度学习02-pytorch-04-张量的运算函数
  • 【计算机网络】运输层协议解析
  • 分布式锁优化之 使用lua脚本改造分布式锁保证判断和删除的原子性(优化之LUA脚本保证删除的原子性)
  • 全栈项目小组【算法赛】题目及解题
  • 【css3】浏览器内核及其兼容性
  • 2017-08-04 前端日报
  • 2017前端实习生面试总结
  • CAP理论的例子讲解
  • Debian下无root权限使用Python访问Oracle
  • Hibernate【inverse和cascade属性】知识要点
  • jquery ajax学习笔记
  • Mysql优化
  • WinRAR存在严重的安全漏洞影响5亿用户
  • 大整数乘法-表格法
  • 后端_ThinkPHP5
  • 计算机常识 - 收藏集 - 掘金
  • 记一次删除Git记录中的大文件的过程
  • 马上搞懂 GeoJSON
  • 排序(1):冒泡排序
  • 使用SAX解析XML
  • 推荐一个React的管理后台框架
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 扩展资源服务器解决oauth2 性能瓶颈
  • ​queue --- 一个同步的队列类​
  • ​十个常见的 Python 脚本 (详细介绍 + 代码举例)
  • # Apache SeaTunnel 究竟是什么?
  • #pragma预处理命令
  • #systemverilog# 之 event region 和 timeslot 仿真调度(十)高层次视角看仿真调度事件的发生
  • #多叉树深度遍历_结合深度学习的视频编码方法--帧内预测
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • (1)(1.13) SiK无线电高级配置(六)
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (3)(3.5) 遥测无线电区域条例
  • (DenseNet)Densely Connected Convolutional Networks--Gao Huang
  • (java)关于Thread的挂起和恢复
  • (超详细)语音信号处理之特征提取
  • (第30天)二叉树阶段总结
  • (二)【Jmeter】专栏实战项目靶场drupal部署
  • (附源码)spring boot车辆管理系统 毕业设计 031034
  • (接口自动化)Python3操作MySQL数据库
  • (十三)Maven插件解析运行机制
  • (一)Thymeleaf用法——Thymeleaf简介
  • (转)eclipse内存溢出设置 -Xms212m -Xmx804m -XX:PermSize=250M -XX:MaxPermSize=356m
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法