【问题标题】:Accessing ServletContext object in Action class in Struts 1.2在 Struts 1.2 的 Action 类中访问 ServletContext 对象
【发布时间】:2014-02-25 06:45:38
【问题描述】:

我得到了一个用例,想出一个解决方案,允许每个用户 ID 配置的用户数在任何给定时间登录到我的应用程序。 例如:userid 'parentuser' 可用于在任何时候最多登录应用程序 10 次。超过此限制后,该用户将不允许登录,因为该用户正在访问该应用程序的最大用户数. 现在,为了实现这一点,我创建了一个上下文侦听器,它将实例化一个属性,当用户在 Action 类中登录应用程序时,我将不断更新该属性。 我的上下文监听器如下:

公共类 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>

问题:我现在如何从我的操作类中访问这个上下文对象“userMap”?如果有人还有其他与此不同的方法,请发布相同的方法。 谢谢

【问题讨论】:

    标签: session servlets struts-1


    【解决方案1】:

    答案在您问题的标题中:将 Map(或包装地图并提供有用方法的对象)存储到 servlet 上下文的属性中(可从事件访问),并从您想要的任何地方检索它: HttpServletRequest 提供对 servlet 上下文的访问。

    如果您的应用程序是集群的,那么更好的解决方案是使用数据库。

    另外,不要忘记在会话到期时递减计数器。

    【讨论】:

      【解决方案2】:

      这可以存储在 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-17
        • 2015-05-22
        • 1970-01-01
        相关资源
        最近更新 更多