Reputation: 13915
I had to modify current code to fit into Spring MVC. I had
HashMap hashmap = new HashMap();
request.setAttribute("dslrErrors", hashmap);
Now I modified the method to pass HashMap back to (method in) controller:
showHTMLResponse method:
@RequestMapping(value = "/s")
public String showHTMLResponse(@ModelAttribute("dslrs") DSLR dslrs[],
@ModelAttribute("dslr") DSLR dslr,
@ModelAttribute("dslrErrors") HashMap<?> dslrErrors,
@ModelAttribute ("dslrform") DSLRForm dslrForm,
@RequestParam("id") String paramId,
@RequestParam("action") String paramAction,
Model model){
// stuff
...
HashMap<String,Object> dslrHashMap = getDSLRById(paramId);
dslr = (DSLR) dslrHashMap.get("dslr");
dslrForm = (DSLRForm)dslrHashMap.get("dslrForm");
dslrErrors = (HashMap<>)dslrHashMap.get("dslrErrors");
...
}
getDSLRById method:
...
HashMap<String,Object> map = new HashMap<String, Object>();
map.put("dslr", dslr);
map.put("dslrform", dslrForm);
map.put("dslrErrors", new HashMap());
return map;
...
Problem:
This line:
dslrErrors = (HashMap<>)dslrHashMap.get("dslrErrors");
and this:
@ModelAttribute("dslrErrors") HashMap<?> dslrErrors
How to properly cast HashMap element/object and assign to Model
so the View
would be able to access it?
Upvotes: 0
Views: 346
Reputation: 2155
The following line does not compile, due to HashMap taking two generic parameters (as said by Tom G in a comment)
@ModelAttribute("dslrErrors") HashMap<?> dslrErrors;
Simply said, I would expect something along the lines of:
@ModelAttribute("dslrErrors") HashMap<?,?> dslrErrors;
The first parameter is the key, the second parameter is the value.
An example of how the above would like in an instantiation situation:
HashMap<?,?> myMap = new HashMap<String, String>();
And one last note to add to that; unless you need hashmap specific methods, prefer to use the interface as a best practise, as it makes it easier to switch implementation without changing alot of code
Map<?,?> myMap = new HashMap<String, String>();
@ModelAttribute("dslrErrors") Map<?,?> dslrErrors;
As for the other line of code;
dslrErrors = (HashMap<>)dslrHashMap.get("dslrErrors");
I can think of 2 ways ontop of my head (don't have an editor in front of me at the moment to verify:
dslrErrors = (HashMap)dslrHashMap.get("dslrErrors"); //no diamond <> operator in the cast
dslrErrors = (HashMap<Object, Object>)dslrHashMap.get("dslrErrors"); //note how we specify the type in the diamond operator here
I hope this helps you. Feel free to ask if any question remains.
Some source about programming to an interface: Program to an interface
Upvotes: 1