Spring MVC - How to get all request params in a map in Spring controller?

Sample URL:

../search/?attr1=value1&attr2=value2&attr4=value4

I do not know the names of attr1, att2, and attr4.

I would like to be able to do something like that (or similar, don't care, just as long as I have access to the Map of request param name -> value:

@RequestMapping(value = "/search/{parameters}", method = RequestMethod.GET)
public void search(HttpServletRequest request, 
@PathVariable Map<String,String> allRequestParams, ModelMap model)
throws Exception {//TODO: implement}

How can I achieve this with Spring MVC?


While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
        @RequestParam Map<String,String> allRequestParams,
        ModelMap model
) {
    return "viewName";
}

Edit

It has been pointed out that there exists (at least as of 3.0) a pure Spring MVC mechanism by which one could get this data. I will not detail it here, as it is the answer of another user. See @AdamGent's answer for details, and don't forget to upvote it.

In the Spring 3.2 documentation this mechanism is mentioned on both the RequestMapping JavaDoc page and the RequestParam JavaDoc page, but prior, it is only mentioned in the RequestMapping page. In 2.5 documentation there is no mention of this mechanism.

This is likely the preferred approach for most developers as it removes (at least this) binding to the HttpServletRequest object defined by the servlet-api jar.

/Edit

You should have access to the requests query string via request.getQueryString().

In addition to getQueryString, the query parameters can also be retrieved from request.getParameterMap() as a Map.


Here's a simple example of getting requestParams in a Map:

@RequestMapping(value="submitForm.html", method=RequestMethod.POST)
public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) {
    String name  = reqParam.get("studentName");
    String email = reqParam.get("studentEmail");     
    ModelAndView model = new ModelAndView("AdmissionSuccess");
    model.addObject("msg", "Details submitted by you::Name: " + name
                                                + ", Email: " + email );
}

In this case, it will bind the values:

  • studentName with name
  • studentEmail with email

The HttpServletRequest object provides a map of parameters already. See request.getParameterMap() for more details.


you can simply use this:

Map<String, String[]> parameters = request.getParameterMap();

That should work fine