I am using Spring MVC RequestMapping
here for GET
parameters. Below is my code -
@RequestMapping(value = "index", method = RequestMethod.GET)
public HashMap<String, String> handleRequest(@RequestParam("dc1Servers") String dc1Servers, @RequestParam("dc2Servers") String dc2Servers, @RequestParam("dc3Servers") String dc3Servers) {
HashMap<String, String> model = new HashMap<String, String>();
String helloWorld = "Hello World!";
model.put("greeting", helloWorld);
System.out.println(dc1Servers);
System.out.println(dc2Servers);
System.out.println(dc3Servers);
return model;
}
I am hitting this URL - http://127.0.0.1:8080/dataweb/index?dc1Servers=3&dc2Servers=3&dc3Servers=3
then it goes into the above code and prints out 3
on the console for all the print and works fine.
Now if you see, I have dc1
, dc2
and dc3
.
So for dc1
, I would like to send these in the URL as the parameters-
dc1Servers=3
dc1HostA
dc1HostB
dc1HostC
dc1IPAddresssA
dc1IPAddresssB
dc1IPAddresssC
Similarly for dc2
, I would like to send these in the URL as the parameters-
dc2Servers=3
dc2HostA
dc2HostB
dc2HostC
dc2IPAddresssA
dc2IPAddresssB
dc2IPAddresssC
Similarly for dc3
, I would like to send these in the URL as the parameters-
dc3Servers=3
dc3HostA
dc3HostB
dc3HostC
dc3IPAddresssA
dc3IPAddresssB
dc3IPAddresssC
Now I am not sure how would I construct an URL for this use case and how would my method will look like? I would like to send them in one single URL call.
Is this use case possible to do using Spring MVC?
You could pass the parameters any way you see fit, one way is to pass them by their natural grouping like this:
http://127.0.0.1:8080/dataweb/index?dc1Server=dc1HostA,dc1IPAddressA&dc1Server=dcHostB,dc1IPAddressB....
By using the same parameter name for each group you'd need to use a
MultiValueMap
. AMultiValueMap
is more or less aMap<String, List<String>>
, so parameters with the same name(dc1Server, dc2Server, etc) would be in the same list. You would use this to get a full list of the params you passed in like this:Then you'd have 3 keys,
dc1Server
would contain all the dc1Server data,dc2Server
all the dc2Server etcCould look into using
@ModelAttribute
if you want to do direct mapping to domain objects: LinkEDIT
Url parameters are strings, so your options for passing a variable number of strings are:
Encode your values in a single url parameter
The simplest way is to use delimiter characters if you know your values will never contain them. Given you're trying to pass ip addresses and host names, this should work for you:
&dc1Servers=dc1HostA,dc1IPAddressA,dc1HostB,dc1IPAddressB
, etc.Pass the same url parameter multiple times
Put the
@RequestParam
annotation on a method arg of typeString[]
, and pass that url parameter multiple times:&dc1Host=dc1HostA&dc1IPAddress=dc1IPAddressA&dc1Host=dc1HostB&dc1IPAddress=dc1IPAddressB
, etc.Here are some more details on this approach: How to pass post array parameter in Spring MVC