ak123
ak123

Reputation: 295

Spring MVC binding request parameters

I wrote a spring-mvc controller method to get an array of values in the request parameter.The method looks like below

/**
 Trying to get the value for request param foo which passes multiple values

**/
@RequestMapping(method=RequestMethod.GET)
public void performActionXX(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam("foo") String[] foo) {

......
......

}

The above method works fine when the request url is in below format

...?foo=1234&foo=0987&foo=5674.

However when the request url is in below format the server returns 400 error

...?foo[0]=1234&foo[1]=0987&foo[2]=5674

Any idea how to fix the method to cater to the second format request url?

Upvotes: 0

Views: 965

Answers (2)

ak123
ak123

Reputation: 295

I resolved this issue using the request.getParameterMap().Below is code.

Map<String,String> parameterMap=  request.getParameterMap();
    for(String key :parameterMap.keySet()){
        if(key.startsWith("nameEntry")){
            nameEntryLst.add(request.getParameter(key));
        }
    }

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

This is not possible with @RequestParam. What you can do is implement and register your own HandlerMethodArgumentResolver to perform to resolve request parameters like

...?foo[0]=1234&foo[1]=0987&foo[2]=5674

into an array. You can always checkout the code of RequestParamMethodArgumentResolver to see how Spring does it.

Note that I recommend you change how the client creates the URL. The server is supposed to define an API and the client is meant to follow it, that's why we have the 400 Bad Request status code.

Upvotes: 1

Related Questions