计算servlet中Web App中的用户数

时间:2012-07-23 04:36:51

标签: java servlets

我修改了我的应用程序以找出下面是Web应用程序中登录的用户数量是我的代码..

听众类

    import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


public class SessionCounter implements HttpSessionListener
{
        private static int count;

        public static int getActiveSessions() {
            return count;
            }



        public SessionCounter()
        {
        }

//The "sessionCount" attribute which has been set in the servletContext should not be modified in any other part of the application. 
//Since we are using serveltContext in both the methods to modify the same variable, we have synchronized it for consistency.


        public void sessionCreated(HttpSessionEvent e)
        {
                count++;
                ServletContext sContext = e.getSession().getServletContext();
                synchronized (sContext)
                {
                        sContext.setAttribute("sessionCount", new Integer(count));
                }
        }

        public void sessionDestroyed(HttpSessionEvent e)
        {
                count--;
                ServletContext sContext = e.getSession().getServletContext();
                synchronized (sContext)
                {
                        sContext.setAttribute("sessionCount", new Integer(count));
                }
        }
}

主servlet是..

package com.saral;

import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
//@WebServlet("/First")
public class MyServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    static final Logger logger = Logger.getLogger(MyServlet.class);


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PropertyConfigurator.configure("log4j.properties");
        logger.info("before---->");

        // TODO Auto-generated method stub
        String name=request.getParameter("txtName");
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        out.println("Hello,"+name);
        out.println("<br> this output is generated by a simple servlet.");
        out.println("Total Number of users logged in--->"+SessionCounter.getActiveSessions());
        out.close();


    }

}

并且web.xml是......

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FirstDemo</display-name>


  <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
</context-param>


  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.saral.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/helloServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>home.html</welcome-file>
  </welcome-file-list>


  <listener>
  <listener-class>com.saral.SessionCounter</listener-class>
</listener>

</web-app>

但我得到的用户总数为0,这并不完美,请告知我哪里错了,我该如何克服呢。

1 个答案:

答案 0 :(得分:0)

当客户端请求到达Tomcat服务器并且您没有调用request.getSession()时,Tomcat服务器stil会自动创建会话。之后,调用SessionCounter类中的方法sessionCreated(...)

会话被销毁时将调用方法sessionDestroyed(...)。当您致电session.invalidate()时会发生这种情况。如果关闭浏览器上的选项卡或关闭浏览器,则tomcat服务器上的会话仍处于活动状态。

我是这么认为的。您可以使用一些不同的侦听器来归档您的目标:HttpSessionAttributeListenerHttpSessionBindingListener,...