如何在Spring Boot控制器中接受GET请求的LocalDateTime参数?

5
这个问题与这个SO问题非常相似,该问题是针对旧的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>()
2个回答

7

请使用@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;
}

1
尝试在您的pointInTime参数之前添加@RequestParam

虽然我已经使用@RequestParam正确地获取了它,但根据OP的要求,我希望它能够作为@PathParam工作。对此有什么想法吗? - Shubham A.
@PathParam 属于 javax.ws.rs 包,如果您打算使用 Spring 开发 REST Web 服务,则应使用 @RequestParam(或任何其他 Spring 注释)。如果您使用 Jetty,则应首选使用 @PathParam - sensitive_piece_of_horseflesh
@ShubhamA。好的,我不确定,但是如果尝试使用@PathVariable呢? - Kadzhaev Marat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接