7

Sample URL:

../get/1?attr1=1&attr2=2&attr3=3

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

When I ran this code, I get the size of 'allRequestParams' equals to 1

@RequestMapping(value = "/get/", method = RequestMethod.GET)
public String search(
@RequestParam Map<String,Integer> allRequestParams) {
   System.out.println(allRequestParams.size());
   return "";
}

Is it problem with Spring or I wrote a wrong code. Thank you!

Mourad Karim
  • 161
  • 1
  • 1
  • 11
  • what are the types of your request parameter values? Are they all `Integer`s. Try changing your map to be of type `` – Sam Yuyitung Mar 16 '17 at 01:40
  • The values are Integers. I tested with String but I did not get the expected size( map size must be 3) – Mourad Karim Mar 16 '17 at 02:16
  • Possible duplicate of [Spring MVC - How to get all request params in a map in Spring controller?](http://stackoverflow.com/questions/7312436/spring-mvc-how-to-get-all-request-params-in-a-map-in-spring-controller) – rvit34 Mar 16 '17 at 06:09

3 Answers3

6

If you are passing the request attributes in the form of query parameters then you can directly get it using HttpServletRequest. Pass in as the parameter to your method and use it like httpServletRequest.getParameterMap(). This will return an immutable java.util.Map of request parameters. Each entry of the map will have the key of type String and value of type String[]. So if you have only one value you can directly access as entry.getValue()[0] would give you the first value. Code looks something like this to access the values.

@RequestMapping(value = "/get/", method = RequestMethod.GET) 
public String search(HttpServletRequest httpServletRequest) {
   Map<String, String[]> requestParameterMap = httpServletRequest.getParameterMap();
   for(String key : requestParameterMap.keySet()){
        System.out.println("Key : "+ key +", Value: "+ requestParameterMap.get(key)[0]);
   }
   return "";
}

Hope this helps !!

Sampath
  • 599
  • 5
  • 12
4

You can define a POJO which contains a map.. Something like below:

@RequestMapping(value = "/get/{searchId}", method = RequestMethod.POST)
public String search(
@PathVariable("searchId") Long searchId,
@RequestParam SearchRequest searchRequest) {
 System.out.println(searchRequest.getParams.size());
 return "";
}

public class SearchRequest {   
private Map<String, String> params;
}

Request Object:

"params":{
     "birthDate": "25.01.2011",
    "lang":"en"       
 }
Tiny
  • 683
  • 5
  • 18
  • 36
3

For your specific example aren't you missing a @PathVariable to access Path variable with value "1" in your example URL?

@RequestMapping(value = "/get/{searchId}", method = RequestMethod.GET)
public String search(
@PathVariable("searchId") Long searchId,
@RequestParam Map<String,String> allRequestParams) {
   System.out.println(allRequestParams.size());
   return "";
}

Also, are you importing java.util.Map?