栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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).
    }



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号