2014-02-25 48 views
1

我已經給出了一個用例,想出一個解決方案,允許在任何給定時間將配置的每個用戶id的用戶數登錄到我的應用程序。 例如:userid'parentuser'可用於在任何時間最多10次登錄應用程序。在此限制之後,用戶將無法登錄,因爲最大用戶數正在訪問該應用程序用戶。 現在,爲了實現這一點,我創建了一個上下文監聽器,它將實例化一個屬性,我將在用戶登錄Action類中的應用程序時繼續更新該屬性。 我的語境收聽是下:在Struts 1.2的Action類中訪問ServletContext對象

公共類ApplicationContextListener實現了ServletContextListener {

private Map<String, List<ApplicationContextBean>> userMap; 

@Override 
public void contextDestroyed(ServletContextEvent arg0) { 
    userMap = null; 
} 

@Override 
public void contextInitialized(ServletContextEvent event) { 
    userMap = new HashMap<String, List<ApplicationContextBean>>(); 
} 

public Map<String, List<ApplicationContextBean>> getUserMap() { 
    return userMap; 
} 

public void setUserMap(Map<String, List<ApplicationContextBean>> userMap) { 
    this.userMap = userMap; 
} 

}

的web.xml是下

<listener> 
    <listener-class>com.pcs.bpems.portal.listener.ApplicationContextListener</listener-class> 
</listener> 

問題:如何我現在可以訪問這個c ontext對象'us​​erMap'從我的操作類?如果任何人有其他方法也不同,請寄出相同的。 感謝

回答

0

這可以被存儲在Servlet上下文如下:

@Override 
public void contextInitialized(ServletContextEvent event) { 
    userMap = new HashMap<String, Map<String,List<ApplicationContextBean>>>(); 
    event.getServletContext().setAttribute(ApplicationConstants.LOGGED_IN_USERS, userMap); 
} 

所存儲的參數可以是然後從HttpSession對象取出作爲下:

currentSession.getServletContext().getAttribute(LOGGED_IN_USERS) 
2

答案就在你的問題的標題:存儲地圖(或物體包裹在地圖,並提供有用的方法)到servlet上下文的屬性(從事件訪問),以及從哪裏檢索你想要:HttpServletRequest提供對servlet上下文的訪問。

一個更好的解決方案,如果您的應用程序被羣集,也可以使用該數據庫。

另外,當會話過期時,不要忘記減少計數器。