猿问

@RequestParam 接收到的加号(+)被替换为空白

我正在尝试使用 @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 格式。如何正确获得加号?


天涯尽头无女友
浏览 242回答 3
3回答

森林海

url参数必须编码调用者有责任这样做。如果调用者使用 Java,他可以简单地将值设置为:URLEncoder.encode("2019-08-19 000:00:00.000+0000", "UTF-8");这将解决2019-08-19%2000:00:00.000%2B0000

繁花如伊

这是已知行为,您可以发送%2B而不是+http://localhost:8989/api/v1/test?date=2019-08-19%2000:00:00.000%2B0000执行此翻译的嵌入式 tomcat 服务器和 spring 甚至不参与此操作。如类代码中所示,没有配置可以更改此行为。所以你必须忍受它

慕容708150

这是我笔记本电脑上的快速测试。我的控制器&nbsp;@GetMapping(value = "/api/{version}/test", produces = "application/json")&nbsp; &nbsp; public SuccessResult getFreeList(@PathVariable String version,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date date) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(date);&nbsp; &nbsp; &nbsp; &nbsp; SuccessResult result = new SuccessResult();&nbsp; &nbsp; &nbsp; &nbsp; result.setDate(date);&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }我的输出对象public class SuccessResult {&nbsp; &nbsp; String message = "success";&nbsp; &nbsp; Date date;&nbsp; &nbsp; public Date getDate() {&nbsp; &nbsp; &nbsp; &nbsp; return date;&nbsp; &nbsp; }&nbsp; &nbsp; public void setDate(Date date) {&nbsp; &nbsp; &nbsp; &nbsp; this.date = date;&nbsp; &nbsp; }&nbsp; &nbsp; public String getMessage() {&nbsp; &nbsp; &nbsp; &nbsp; return message;&nbsp; &nbsp; }&nbsp; &nbsp; public void setMessage(String message) {&nbsp; &nbsp; &nbsp; &nbsp; this.message = message;&nbsp; &nbsp; }}到达端点的 urlhttp://localhost:8080/api/v1/test?date=2019-08-19T00:00:00.000%2B00:00结果{"message":"success","date":1566172800000}
随时随地看视频慕课网APP

相关分类

Java
我要回答