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

JavaSpringSpring Mvc

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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";
}

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

you can simply use this:

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

That should work fine

Solution 6 - Java

Use org.springframework.web.context.request.WebRequest as a parameter in your controller method, it provides the method getParameterMap(), the advantage is that you do not tight your application to the Servlet API, the WebRequest is a example of JavaEE pattern Context Object.

Solution 7 - Java

There are two interfaces

  1. org.springframework.web.context.request.WebRequest
  2. org.springframework.web.context.request.NativeWebRequest

Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.

Ex.:

@RequestMapping(value = "/", method = GET)
public List<T> getAll(WebRequest webRequest){
    Map<String, String[]> params = webRequest.getParameterMap();
    //...
}

P.S. There are Docs about arguments which can be used as Controller params.

Solution 8 - Java

I might be late to the party, but as per my understanding , you're looking for something like this :

for(String params : Collections.list(httpServletRequest.getParameterNames())) {
    // Whatever you want to do with your map
    // Key : params
    // Value : httpServletRequest.getParameter(params)                
}

Solution 9 - Java

@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
	jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

All params will be stored in jsonObject.

Solution 10 - Java

There is fundamental difference between query parameters and path parameters. It goes like this: www.your_domain?queryparam1=1&queryparam2=2 - query parameters. www.your_domain/path_param1/entity/path_param2 - path parameters.

What I found surprising is that in Spring MVC world a lot of people confuse one for the other. While query parameters are more like criteria for a search, path params will most likely uniquely identify a resource. Having said that, it doesn't mean that you can't have multiple path parameters in your URI, because the resource structure can be nested. For example, let's say you need a specific car resource of a specific person:

www.my_site/customer/15/car/2 - looking for a second car of a 15th customer.

What would be a usecase to put all path parameters into a map? Path parameters don't have a "key" when you look at a URI itself, those keys inside the map would be taken from your @Mapping annotation, for example:

@GetMapping("/booking/{param1}/{param2}")

From HTTP/REST perspective path parameters can't be projected onto a map really. It's all about Spring's flexibility and their desire to accommodate any developers whim, in my opinion.

I would never use a map for path parameters, but it can be quite useful for query parameters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMDbView Question on Stackoverflow
Solution 1 - JavaAdam GentView Answer on Stackoverflow
Solution 2 - Javanicholas.hauschildView Answer on Stackoverflow
Solution 3 - JavaShrirang KadaleView Answer on Stackoverflow
Solution 4 - JavaKevinView Answer on Stackoverflow
Solution 5 - JavaBiggy_javaView Answer on Stackoverflow
Solution 6 - JavaDiego Lins de FreitasView Answer on Stackoverflow
Solution 7 - JavakatoquroView Answer on Stackoverflow
Solution 8 - JavagoelanshulView Answer on Stackoverflow
Solution 9 - JavaAgyaey TiwariView Answer on Stackoverflow
Solution 10 - JavayuranosView Answer on Stackoverflow