【问题标题】:Spring ServletUriComponentsBuilder and square brackets in query paramsSpring ServletUriComponentsBuilder 和查询参数中的方括号
【发布时间】:2018-04-22 21:12:58
【问题描述】:

我正在尝试使用 Spring 的 ServletUriComponentsBuilder 从当前请求创建分页 nextprev 链接。

我遇到的问题是 ServletUriComponentsBuilder.fromCurrentRequest() 不是未编码百分比编码的值,例如:

http://example.com/articles?page%5Bnumber%5D=2

问题是使用可以调用带有未编码方括号的页面,例如http://example.com/articles?page[number]=2,没有任何问题。

Spring Data 在其可分页参数解析器中接受两种变体(未编码方括号和已编码方括号)。 这是因为在水下使用 Coyote Web 请求获取参数,其中包含未编码的参数名称。

Spring 的 @RequestParam("page[number]") 也可以毫无问题地接受像 http://example.com/articles?page%5Bnumber%5D=2 这样的编码请求。

从服务器端,我总是希望根据 RFC 3986 返回百分比编码的 url。

但似乎没有办法做到这一点,因为UriComponents 查询参数可能包含两个编码的编码未编码的名称。因为对此,如果我在构建器上调用encode(),则已编码的查询参数将再次编码,但如果包含未编码的名称toURI() 将失败,因为不允许未编码的[

请注意,url 可能包含除分页之外的多个查询参数,例如用于过滤。

请求可能如下:

http://example.com/articles?filter[category]=food

并且会返回带有编码next 链接的响应,例如:

http://example.com/articles?page%5Bnumber%5D=2&filter%5Bcategory%5D=food

我的解决方法是忽略 ServletUriComponentsBuilder 并简单地获取请求 url 并执行自定义正则表达式替换。

【问题讨论】:

    标签: spring spring-mvc spring-data spring-hateoas


    【解决方案1】:

    我知道这是一个较老的问题,您也找到了解决方法。但是您是否尝试过使用ServletUriComponentsBuilderbuild() 方法? 如下某种:

    ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
    

    我在处理 JSON 字符串时遇到了一些问题,这很有帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2023-03-20
      • 2020-10-26
      • 2016-08-23
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多