2010-05-24 58 views
2

我正在嘗試使用Spring MVC製作這個2人遊戲的網頁遊戲應用程序。我有會話範圍的bean Player和應用程序範圍的bean GameList,它創建並存儲Game實例並將它們傳遞給Players。玩家創建一個遊戲並從GameList獲得其ID,其他玩家將ID發送到GameList並獲取Game實例。 Game實例將其播放器作爲屬性。問題是每個玩家只能看到自己而不是另一個。每個玩家看到什麼我可以從應用程序範圍的bean訪問Spring會話範圍的bean嗎?怎麼樣?

例子:

  1. 第一的球員(愛麗絲)創建了一個遊戲:Creator: Alice, Joiner: Empty
  2. 第二個玩家(BOB)加入遊戲:Creator: Bob, Joiner: Bob
  3. 首先玩家刷新她的瀏覽器Creator: Alice, Joiner: Alice

我想讓他們看到的是Creator: Alice, Joiner: Bob。實現這一點的簡單方法是保存關於玩家的信息,而不是引用玩家,但遊戲對象需要調用玩家對象的方法,所以這不是解決方案。

我認爲這是因爲session-scoped Player bean的aop:scoped-proxy。如果我理解了這一點,Game對象就引用了代理,它引用了當前會話的Player對象。遊戲實例能以某種方式保存/訪問其他玩家對象嗎?

調度-servlet.xml中:

<bean id="userDao" class="authorization.UserDaoFakeImpl" /> 
<bean id="gameList" class="model.GameList" /> 
<bean name="/init/*" class="controller.InitController" > 
    <property name="gameList" ref="gameList" /> 
    <property name="game" ref="game" /> 
    <property name="player" ref="player" /> 
</bean> 
<bean id="game" class="model.GameContainer" scope="session"> 
     <aop:scoped-proxy/> 
</bean> 
<bean id="player" class="beans.Player" scope="session"> 
     <aop:scoped-proxy/> 
</bean> 

方法controller.InitController

private GameList gameList; 
private GameContainer game; 
private Player player; 
public ModelAndView create(HttpServletRequest request, 
     HttpServletResponse response) throws Exception {   
    game.setGame(gameList.create(player));   
    return new ModelAndView("redirect:game"); 
} 
public ModelAndView join(HttpServletRequest request, 
     HttpServletResponse response, GameId gameId) throws Exception { 
    game.setGame(gameList.join(player, gameId.getId()));  
    return new ModelAndView("redirect:game"); 
} 

調用的方法model.gameList

public Game create(Player creator) {   
    Integer code = generateCode();   
    Game game = new Game(creator, code); 
    games.put(code, game); 
    return game; 
} 
public Game join(Player joiner, Integer code) { 
    Game game = games.get(code); 
    if (game!=null) { 
     game.setJoiner(joiner);   
    } 
    return game; 
} 
+0

@Pascal Thivent:我看不出這個問題與jsp-tags有什麼關係,但無論如何......你是老闆:-P – 2010-05-25 23:32:33

+0

這只是一個錯誤,由於自動完成,現在修復。 – 2010-05-26 12:25:06

回答

1

我相信你是正確的代理是爲什麼你只看到你自己。對代理的任何引用都將僅適用於會話中的對象。

您是否需要將遊戲和 玩家作爲會話範圍?您嘗試在會話中使用它們 的事實 指示 它們不是會話範圍數據。您可以從工廠創建它們並將它們的引用存儲在會話範圍的bean中。

或者,如果您確實希望播放器是會話作用域,則可以在會話bean中包裝對原型的引用。然後,您可以使用您的跨會話數據的原型參考,以及任何會話特定本地數據的會話bean。

有幾種方法可以解決這個問題,但實際上您需要將跨會話數據移出會話範圍的bean,並移入可共享的應用程序範圍bean。

0

你不能在HTTP會話中擁有遊戲數據,因爲它只屬於一個用戶。

您需要在創建者和joiner的會話中存儲對遊戲的引用。

2

您不能從應用程序範圍訪問不同的會話範圍的bean。

但是,你可以做其他方式 - ,(通過調用addPlayer(..)

0

是註冊在應用程序範圍的bean中的每個球員,最簡單的方法就是用下面的註解創建代理:

@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) 

可從Spring 3.1獲得。在舊的時代,你必須在XML配置中使用aop:scoped-proxy標籤

相關問題