【问题标题】:Why am I getting "400 Bad Request" for this URL in Spring MVC?为什么我在 Spring MVC 中收到此 URL 的“400 Bad Request”?
【发布时间】:2014-05-27 09:29:38
【问题描述】:

以下 URL 导致“400 错误请求”:

http://localhost:8080/springdata_web/rest/errors/test?from=2014-05-25T00:00:00.000Z&to=2014-05-27T00:00:00.000Z

匹配的@RequestMapping 如下。我可以看到我肯定会使用这种方法,因为我在控制台中看到了 Sysout 行,例如使用以下 URL:

http://localhost:8080/springdata_web/rest/errors/test?from=&to=

所以我想这与 Date 类型和 Spring 不接受我在请求参数中传递的格式有关,但我不明白为什么。

@RequestMapping(value = "/test",
        method = RequestMethod.GET,
        produces = "application/json")
@ResponseBody
public Resource<List<ErrorsDTOEntity>> getAllErrors(
        @RequestParam(value = "from", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date from, 
        @RequestParam(value = "to", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date to) {
    System.out.println("getAllErrors(Date, Date);");
    List<ErrorsDTOEntity> services = errorsDAO.getAllErrors(from, to);
    Resource<List<ErrorsDTOEntity>> toReturn = new Resource<List<ErrorsDTOEntity>>(services);
    toReturn.add(linkTo(methodOn(ErrorsController.class).getAllErrors(from, to)).withSelfRel());
    return toReturn;
}

【问题讨论】:

    标签: spring datetime spring-mvc iso


    【解决方案1】:

    这是 URL 中日期的格式。此 URL 编码请求有效:

    http://localhost:8080/springdata_web/rest/errors/test?from=2014-05-25T00%3A00%3A00.000%2B0000&amp;to=2014-05-27T00%3A00%3A00.000%2B0000

    【讨论】:

      【解决方案2】:

      您传递的日期模式(从/到)不匹配。底层模式是 DateTimeFormat.ISO DATE_TIME

      yyyy-MM-dd'T'hh:mm:ss.SSSZ

      所以示例时间如下:

      2000-10-31T01:30:00.000-05:00

      尝试以下请求是否有效: 测试?从=2000-10-31T01:30:00.000-05:00&to=2000-10-31T01:30:00.000-05:00

      Spring Docs 说:

      【讨论】:

      • @conorgriffin - 你能在下面的采样时间 - 2011-07-11T21:28:59.564+01:00
      • 在此处添加 T 而不是空格
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2015-09-19
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多