Reputation: 173
I have some class named Configuration that have some fields of types java.util.List and java.util.Map.
public class Configuration {
List<String> objects;
Map<String, Integer> maps;
// getters, setters...
}
I have some jsp page where user can edit this fields.
With List i have no problems, i just name my input field same as field named in class and spring converts it in @ModelAttribute.
<input type="text" name="objects"/>
<input type="text" name="objects"/>
<input type="text" name="objects"/>
With Map i have some probmels - i don't know how to name my input field for key and for value. When i'm naming them like key and value i get null in servlet.
<input type="text" name="key"/><input type="text" name="value"/>
Wnen i'm naming them like maps.key and maps.value i get empty map in servlet
<input type="text" name="maps.key"/><input type="text" name="maps.value"/>
when i'm naming them like maps i get spring converting error
<input type="text" name="maps"/><input type="text" name="maps"/>
What the correct way to pass map from jsp to servlet?
Upvotes: 1
Views: 2180
Reputation: 12942
you can use spring:bind tag to help you check this link and this link
Upvotes: 0
Reputation: 279960
I wouldn't let Spring do this for you. I don't know if it can go that deep.
In your jsp, maybe you have a javascript button that adds an <input>
field for Integers (assuming Map<String, Integer>
) every time you want to add one. You should be able to set the name attribute of this field and always use some specific prefix. For example, use the prefix NUMBER_OF_
. Then a field would become, eg., NUMBER_OF_players
, where players
is a value you provided. So the input would look like:
<input type="text" name="NUMBER_OF_players" />
In your controller, pass the HttpServletRequest
to your handler method and call getParameterMap()
Map<String, String[]> parameterMap = request.getParameterMap();
for (String key: parameterMap.keySet()) {
if (key.startsWith("NUMBER_OF_")) {
parameterKeyList.add(key); // add it to a list of parameters that are going to be
// used for your Configuration instance
// you know this is a good one because it has the prefix
}
}
Map<String, Integer> maps = ...;
for (String parameter : parameterKeyList) {
String value = request.getParameter(parameter);
Integer integer = Integer.parseInt(value);
maps.put(parameter, integer);
}
Configuration config = new Configuration();
config.setMaps(maps);
I've not added all the null
checks and exception handling, I leave that to you.
You could possibly let Spring generate part of the Configuration
instance (the fields that are known), then do the rest yourself with the above.
Upvotes: 3