Spring MVC populate @RequestParam Map

后端 未结 4 1168
轻奢々
轻奢々 2020-12-19 01:58

I have the following method in my Spring MVC @Controller :

@RequestMapping(method = RequestMethod.GET)
public String testUrl(@RequestParam(value=\"test\") Ma         


        
4条回答
  •  独厮守ぢ
    2020-12-19 02:48

    Your question needs to be considered from different points of view.

    1. first part:

    as is mentioned in the title of the question, is how to have Map as @RequestParam.

    Consider this endpoint:

    @GetMapping(value = "/map")
    public ResponseEntity getData(@RequestParam Map allParams) {
        String str = Optional.ofNullable(allParams.get("first")).orElse(null);
        return ResponseEntity.ok(str);
    }
    

    you can call that via:

    http://:/child/map?first=data1&second=data2
    

    then when you debug your code, you will get these values:

    > allParams (size = 2)
        > first = data1
        > second = data2
    

    and the response of the requested url will be data1.


    1. second part:

    as your requested url shows (you have also said that in other answers' comments) ,you need an array to be passed by url.

    consider this endpoint:

    public ResponseEntity getData (@RequestParam("test") Long[] testId,
                                      @RequestParam("notTest") Long notTestId)
    

    to call this API and pass proper values, you need to pass parameters in this way:

    ?test=1&test=2¬Test=3
    

    all test values are reachable via test[0] or test[1] in your code.


    1. third part:

    have another look on requested url parameters, like: test[B]

    putting brackets (or [ ]) into url is not usually possible. you have to put equivalent ASCII code with % sign.

    for example [ is equal to %5B and ] is equal to %5D.

    as an example, test[0] would be test%5B0%5D.

    more ASCII codes on: https://ascii.cl/

提交回复
热议问题