【问题标题】:The plus(+) sign received by @RequestParam is replaced by a blank@RequestParam 收到的加号 (+) 被替换为空白
【发布时间】:2019-12-24 15:17:05
【问题描述】:

我正在尝试使用 @RequestParam 获取 ISO 字符串并将其解析为日期。

使用下面的代码,我尝试使用http://localhost:8989/api/v1/test?date=2019-08-19%2000:00:00.000+0000进行测试

但是结果是400 Bad Request,当我把日期值的类型改为String时,是2019-08-19 00:00:00.000 0000

public class myController {

    @GetMapping(value = "/api/{version}/test", produces = "application/json")
    public ResponseEntity<MyList> getFreeList(
        @PathVariable
        String version,
        @RequestParam("date")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSZ")
        Optional<Date> date) {
            return new ResponseEntity<>(myService.getList(
                date.orElse(null)),
                HttpStatus.OK);
    }
}

我无法更改 URL 格式。如何正确获取加号?

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    网址参数必须为encoded

    调用者有责任这样做。 如果调用者使用Java,他可以简单地将值设置为:

    URLEncoder.encode("2019-08-19 000:00:00.000+0000", "UTF-8");
    

    这将被解决

    2019-08-19%2000:00:00.000%2B0000
    

    【讨论】:

      【解决方案2】:

      这是一个known behavior,你可以发送%2B而不是+

      http://localhost:8989/api/v1/test?date=2019-08-19%2000:00:00.000%2B0000
      

      执行此翻译的嵌入式 tomcat 服务器,而 spring 甚至不参与此操作。如类代码中所示,没有配置可以更改此行为。所以你必须忍受它

      【讨论】:

      【解决方案3】:

      这是我笔记本电脑上的快速测试。我的控制器

       @GetMapping(value = "/api/{version}/test", produces = "application/json")
          public SuccessResult getFreeList(@PathVariable String version,
                  @RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date date) {
              System.out.println(date);
              SuccessResult result = new SuccessResult();
              result.setDate(date);
              return result;
          }
      

      我的输出对象

      public class SuccessResult {
      
          String message = "success";
      
          Date date;
      
          public Date getDate() {
              return date;
          }
      
          public void setDate(Date date) {
              this.date = date;
          }
      
          public String getMessage() {
              return message;
          }
      
          public void setMessage(String message) {
              this.message = message;
          }
      

      }

      到达端点的url

      http://localhost:8080/api/v1/test?date=2019-08-19T00:00:00.000%2B00:00
      

      结果

      {"message":"success","date":1566172800000}
      

      【讨论】:

        猜你喜欢
        • 2011-04-06
        • 1970-01-01
        • 1970-01-01
        • 2015-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多