使用查询参数处理 Spring-boot 过滤器

san*_*016 5 java query-string spring-boot

在 REST 端点中,我想接收过滤器作为查询参数。每个过滤器都定义在以逗号分隔的键值对中,如下所示:

www.example.com/things?filter=key:value,key2:value2,key3:value3

这个例子意味着我想要获取的事物列表必须包含keyas valueaskey2asvalue2 key3value3

在此端点中,我可以接收多个过滤器,如下所示:

www.example.com/things?filter=key:value&filter=key2:value2,key3:value3

这意味着事物列表必须具有keyasvalue ( key2asvalue2key3as value3)

在 spring-boot 中,接收多个同名查询参数的方法是在控制器中定义一个@RequestParam("filter") String[] filters. 但问题是:每当我只发送一个filter查询参数时,我都会得到一个由每个键对值形成的字符串数组。如果我发送多个filter,我将得到一个包含每个过滤器的数组(如预期)。

这意味着对于第一个示例,每个密钥对都会有一个大小为 3 的数组,而在第二个示例中,我会收到一个大小为 2 的数组。

我需要的是,每当我只发送一个filter查询参数时,@RequestParam标签都会传递一个大小为 1 的数组,其中包含稍后要解析的整个字符串。有办法实现这一点吗?

Mis*_*orp 7

可能有更好的方法来实现您所追求的目标,但这是我的建议。

快速概念证明,使用Spring Boot 2.2.1.RELEASE,在单独的行上打印每个过滤器

import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/things")
public class ThingController {

    @GetMapping
    public void filters(@RequestParam MultiValueMap<String, String> filters) {
        System.out.println("Filters:");
        filters.get("filter").forEach(System.out::println);
    }
}
Run Code Online (Sandbox Code Playgroud)

仅使用单个查询参数的curl命令filter

curl -v 'http://localhost:8080/things/?filter=key:value,key2:value2,key3:value3'
Run Code Online (Sandbox Code Playgroud)

印刷:

Filters:
key:value,key2:value2,key3:value3
Run Code Online (Sandbox Code Playgroud)

仅使用多个查询参数的curl命令filter

curl -v 'http://localhost:8080/things/?filter=key:value&filter=key2:value2,key3:value3'
Run Code Online (Sandbox Code Playgroud)

印刷:

Filters:
key:value
key2:value2,key3:value3
Run Code Online (Sandbox Code Playgroud)