【问题标题】:How can determine the time that a particular user has been actually using my application?如何确定特定用户实际使用我的应用程序的时间?
【发布时间】:2016-07-13 18:02:43
【问题描述】:

我在 Tomcat 8 上部署了一个 Web 应用程序。我想跟踪特定用户使用我的应用程序的时间——定义为该用户执行每个请求所花费的时间。也就是说,系统中有效工作的时间。

Tomcat 中是否已经存在这样的功能?

在 Tomcat 中,我已经可以看到 Used TimeInactive Time 可用于Tomcat Manager application,但 used time 不可用我在找什么:它只是减去 Creation TimeLast Accessed Time 给出“总会话有效年龄”。

如何确定用户的实际使用时间?

【问题讨论】:

标签: tomcat web-applications


【解决方案1】:

您想使用Filter 记录每个请求的时间,然后将该时间添加到用户的总使用时间中。您可以将其存储在用户的HttpSession 中,假设已经有可用的会话。

请注意,如果您仅将其存储在会话中,则一旦会话到期,用户的累积使用时间将丢失。如果您希望信息在会话到期后仍然存在,则需要将使用时间写入其他地方,例如磁盘上的文件或关系数据库。

@angryip 在上面的评论中给出的参考是Filter 的一个很好的例子,但对于如何实际为请求计时并不是一个很好的例子。 FilterdoFilter 方法可以非常简单。像这样的:

public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain)
    throws IOException, ServletException
{
    HttpSession session = null;

    if(request instanceof HttpServletRequest)
        session = ((HttpServletRequest)request).getSession(false);

    // Start the clock
    long elapsed = System.currentTimeMillis();

    // Use try/finally because the request can throw an exception;
    // We still want to capture the usage-time even if an error
    // occurs.
    try {
        chain.doFilter(request, response);
    } finally {
        // Stop the clock
        elapsed = System.currentTimeMillis() - elapsed;

        // Store the cumulative usage time in the session
        if(null != session) {
            Long usage = (Long)session.getAttribute("usage");
            if(null != usage)
                elapsed = elapsed + usage.getLong();
            session.setAttribute("usage", Long.valueOf(elapsed));
        }
    }
}

从会话中获取信息取决于您。您可以使用JMX 通过其标识符请求会话然后使用“usage”参数调用“getAttribute”来观察它。

【讨论】:

  • 谢谢。但是,还有一个问题。这个过滤器,能不能离开重载的应用程序?我以为在 TomCat 中已经准备好了一些东西。
  • 不,Tomcat 不提供开箱即用的任何东西。构建后,您可以在任何您喜欢的应用程序中使用此Filter,但不能可靠地使用它来汇总多个应用程序的使用情况(因为使用信息存储在HttpServlet 中)。如果您将使用信息存储在其他地方,则可以汇总任意数量的应用程序的使用时间,只要您能弄清楚“用户”是谁。
猜你喜欢
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多