Get请求JAVA中的LocalDate格式

时间:2017-01-07 10:21:56

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

我正在为我的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);
    }

现在我正在测试这个,

  

/休息/管理/ restaurant_representation?ID = 1004

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

  

/休息/管理/ restaurant_representation日期2015-05-05 =&安培;?ID = 1004

它显示了这个:

  

客户端发送的请求在语法上是不正确的。

哪种LocalDate格式正确?

2 个答案:

答案 0 :(得分:4)

我们需要使用@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);
}

答案 1 :(得分:4)

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

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