【问题标题】:LocalDate format in Get request JAVA获取请求 JAVA 中的 LocalDate 格式
【发布时间】:2017-05-22 01:55:37
【问题描述】:

我正在为我的 Java MVC 应用程序编写一个 REST 接口。这是一个功能:

    @GetMapping(value = "/restaurant_representation", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestaurantRepresentation restaurantRepresent(
        @RequestParam(value = "date", required = false) LocalDate date,
        @RequestParam(value = "id") Integer id) {
            return date == null ?
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, LocalDate.now()) :
                restaurantRepresentationCompiler.compileRestaurantRepresentation(id, date);
    }

现在我正在测试这个,并且

/rest/admin/restaurant_representation?id=1004

这个请求提供了正确的结果,但是当我尝试添加日期参数时

/rest/admin/restaurant_representation?date=2015-05-05&id=1004

它显示了这个:

客户端发送的请求语法错误。

什么 LocalDate 格式是正确的?

【问题讨论】:

    标签: java rest model-view-controller get localdate


    【解决方案1】:

    我们需要使用@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)

    像这样:

        @GetMapping(value = "/restaurant_representation", produces = MediaType.APPLICATION_JSON_VALUE)
        public RestaurantRepresentation restaurantRepresent(
            @RequestParam(value = "date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestParam(value = "id") Integer id) {
                return date == null ?
                    restaurantRepresentationCompiler.compileRestaurantRepresentation(id, LocalDate.now()) :
                    restaurantRepresentationCompiler.compileRestaurantRepresentation(id, date);
    }
    

    【讨论】:

    • 你抢我的答案:)
    【解决方案2】:

    您需要使用@DateTimeFormat 并指定您接受的日期格式。

    @RequestParam(required = false, value = "date") @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate fromDate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      相关资源
      最近更新 更多