【问题标题】:How to accept LocalDateTime param in a GET request to Spring Boot Controller?如何在对 Spring Boot Controller 的 GET 请求中接受 LocalDateTime 参数?
【发布时间】:2017-10-02 12:31:33
【问题描述】:

这个问题与this SO problem 非常相似,后者适用于较早的Date API。

我想用 Java 8 LocalDateTime API 实现同样的效果。当我这样做时,

@RequestMapping("/locationSnapshot/{userId}/{pointInTime}")
public MyResponse getLocationInTime(
        @PathParam(value="userId") Long userId,
        @PathParam(value="pointInTime")
        @DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ss") LocalDateTime pointInTime) {

    MyResponse response = new MyResponse();
    return response;
}

我明白了,

Failed to instantiate [java.time.LocalDateTime]: No default constructor
found; nested exception is java.lang.NoSuchMethodException: 
java.time.LocalDateTime.<init>()

【问题讨论】:

    标签: java spring


    【解决方案1】:

    尝试在pointInTime 参数前添加@RequestParam

    【讨论】:

    • 当我得到这个并且它与@RequestParam 一起正常工作。但根据 OP,我希望它作为@PathParam 工作。有什么想法吗?
    • @PathParam 属于javax.ws.rs 包,如果您打算使用spring 开发REST web 服务,您应该使用@RequestParam(或任何其他spring 注释)。如果您使用码头,应优先使用@PathParam
    • @ShubhamA。好的,我不确定,但如果尝试@PathVariable 会怎样?
    【解决方案2】:

    使用@PathVariable 代替@PathParam

    @RequestMapping("/locationSnapshot/{userId}/{pointInTime}")
    public MyResponse getLocationInTime(
            @PathVariable(value="userId") Long userId,
            @PathVariable(value="pointInTime")
            @DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ss") LocalDateTime pointInTime) {
    
        MyResponse response = new MyResponse();
        return response;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 2018-04-01
      • 2020-07-12
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多