如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”

如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”,第1张

如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”

TL; DR-
您可以使用just捕获它为字符串

@RequestParam
,也可以让Spring也通过
@DateTimeFormat
参数另外将字符串解析为java日期/时间类。

@RequestParam
足以抓住你等号(=)后提供的日期,但是,它涉及到的方法作为
String
。这就是为什么它引发强制转换异常。

有几种方法可以实现此目的:

  1. 自己解析日期,以字符串的形式获取值。

    @GetMapping(“/test”)
    public Page get(@RequestParam(value=”start”, required = false) String start){

    //Create a DateTimeFormatter with your required format:DateTimeFormatter dateTimeFormat =         new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE);//Next parse the date from the @RequestParam, specifying the TO type as

    a TemporalQuery:
    LocalDateTime date = dateTimeFormat.parse(start, LocalDateTime::from);

    //Do the rest of your pre...

    }

  2. 利用Spring的自动分析和期望日期格式的能力:

    @GetMapping(“/test”)
    public void processDateTime(@RequestParam(“start”)
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    LocalDateTime date) {
    // The rest of your pre (Spring already parsed the date).
    }



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5673989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存