简体   繁体   中英

Springboot controller request param for map always null

I'm trying to pass in a bunch of id's to create a filter.

The incoming request looks like (ignoring the pagination stuff, which works fine)

http://localhost:8080/news-items?filter%5B%5D=09c731de-7ed8-385d-849c-f4d6535137ab&filter%5B%5D=dd1ba187-2df9-3985-ad1c-a4cde2dfe669&modelPath=controller.newsItems&page=0&per_page=25

Where the filter param equals an ID, but there is a bunch of them, for example:

filter: [
"09c731de-7ed8-385d-849c-f4d6535137ab",
"dd1ba187-2df9-3985-ad1c-a4cde2dfe669"
],

I can't seem to collect the filters in the controller. At the moment I have

public String getFeeds(@RequestParam(value = "filter", required = false) MultiValueMap<String, String> filter, @RequestParam(value = "page", required = false) int page, @RequestParam(value = "per_page", required = false) int perPage) {
    log.info("Filter: {}", filter);
}

However filter is always null. I've tried using a String rather than a map but that is also always null.

How do I go about accepting an unknown number of params in this manner? I get the feeling this is really simple but I'm just missing the obvious...

Turns out it was simple like I thought. When using a Map in the @RequestParam it takes all the incoming params, regardless of what they are.

So from what I can tell the correct solution is to do something like

@GetMapping(produces = APPLICATION_JSON)
public String getFeeds(@RequestParam MultiValueMap<String, String> params) {

    params.forEach(//something);

}

我认为您正在寻找的只是一个数组或一个列表,如下所示:

public String getFeeds(@RequestParam(value = "filter", required = false) List<String> filters) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM