前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring中使用Date参数

Spring中使用Date参数

作者头像
叔牙
发布2020-11-19 17:41:55
1.5K0
发布2020-11-19 17:41:55
举报

Spring中使用Date参数

介绍

在日常开发中,我们难免会遇到前端向后端传日期参数做查询操作, 在这篇文章中,我们将探索如何在请求和应用程序级别接受Spring REST请求中的Date,LocalDate和LocalDateTime类型参数。

1

问题

假如有一个控制器,它有三个接受Date,LocalDate和LocalDateTime参数的方法:

@RestController public class DateTimeController { @PostMapping("/date") public void date(@RequestParam("date") Date date) { // ... } @PostMapping("/localdate") public void localDate(@RequestParam("localDate") LocalDate localDate) { // ... } @PostMapping("/localdatetime") public void dateTime(@RequestParam("localDateTime") LocalDateTime localDateTime) { // ... } }

当我们使用根据ISO 8601格式化的参数向任何这些方法发送POST请求时,将出现异常。

例如,当将“2018-10-22”发送到/date端点时,我们将收到错误的请求错误,其中包含类似于以下内容的消息:

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException.

这是因为Spring默认情况下无法将String参数转换为任何日期或时间对象。

2

在请求级别转换日期参数

处理此问题的方法之一是使用@DateTimeFormat注解标注参数并提供格式设置模式参数:

@RestController public class DateTimeController { @PostMapping("/date") public void date(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date) { // ... } @PostMapping("/local-date") public void localDate(@RequestParam("localDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate) { // ... } @PostMapping("/local-date-time") public void dateTime(@RequestParam("localDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime localDateTime) { // ... } }

这样的话,如果使用ISO 8601格式格式化字符串,则字符串将正确转换为日期对象。

我们也可以使用自己的转换模式,可以在@DateTimeFormat注释中提供一个模式参数:

@PostMapping("/date") public void date(@RequestParam("date") @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) { // ... }

3

在应用程序级别转换日期参数

在Spring中处理日期和时间对象转换的另一种方法是提供全局配置,我们可以按照官方文档来完成:

@Configuration class DateTimeConfig { @Bean public FormattingConversionService conversionService() { DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setDateFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy")); registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")); registrar.registerFormatters(conversionService); // other desired formatters return conversionService; } }

首先,我们使用false参数创建DefaultFormattingConversionService,这意味着Spring默认情况下不会注册任何日期格式化程序。

然后,我们在DateTimeFormatterRegistrar对象中手动注册日期和日期时间格式的新模式。

总结

在本文中,我们学习了如何接受Spring MVC请求中的日期参数,并且已经介绍了如何根据请求和全局执行此操作。

我们还了解了如何创建自己的日期格式模式。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 PersistentCoder 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档