2016-10-22 20 views
0

在我的控制器意見,我已經把在HttpSession的會議一個模型對象:如何使用@ModelAttribute參數註釋獲取會話中保存的模型?

Map<String, Game> gamesMap = new HashMap<>(); 
gamesMap.put("1", new Game()); 

Games games = new Games(); 
games.setGames(gamesMap); 

session.setAttribute("games", games); 

當我試圖讓與@ModelAttribute參數對象games.getGames()返回我總是空的,而不是我在前面已經設置了gamesMap。

RequestMapping(value = "test", method = RequestMethod.GET) 
public String test(@ModelAttribute("games") Games games) { 
    games.getGames(); // getGames() returns null instead of collection I've set before. 
} 

我做錯了什麼?當我使用會話,並從那裏得到它可以正常工作,但我試圖理解爲什麼它不能與@ModelAttribute更清潔。

回答

0

好的,我發現問題是什麼。如果控制器註釋爲@sessionattributes,Spring只會嘗試將模型屬性綁定到會話參數。如果它沒有發現它創建新的實例,在這種情況下地圖是空的。