-1

以下の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));
                }
        }
}

メインのサーブレットは..

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 として取得しています。これは完全ではありません。どこが間違っているのか、どうすれば克服できるのかを教えてください。

4

1 に答える 1

0

クライアント要求が Tomcat サーバーに届いたときに を呼び出さないrequest.getSession()場合、Tomcat サーバーはセッションを自動的に作成します。その後、sessionCreated(...)SessionCounter クラスのメソッドが呼び出されます。

このメソッドsessionDestroyed(...)は、セッションが破棄されたときに呼び出されます。を呼び出すと発生しますsession.invalidate()。ブラウザーのタブを閉じたり、ブラウザーを閉じたりしても、セッションは Tomcat サーバー上で存続します。

そう思います。いくつかの異なるリスナーを使用して、目標をアーカイブできます: HttpSessionAttributeListener, HttpSessionBindingListener,...

于 2016-04-26T04:03:06.247 に答える