4

晚上好,

在测试 JSF 2.0 Web 应用程序中,我试图获取活动会话的数量,但 HttpSessionListener 的 sessionDestroyed 方法存在问题。确实,当用户登录时,活动会话的数量增加了 1,但是当用户注销时,相同的数量保持不变(不会发生递减),更糟糕的是,当同一用户再次登录时(即使他未验证会话),相同的数字也会增加。换句话说:

1- 我登录,活动会话数增加 1。 2- 我注销(会话未验证) 3- 我再次登录,会话数增加 1。显示 = 2。 4- 我重复操作,并且会话数不断增加,而只有一个用户登录。

所以我认为方法 sessionDestroyed 没有被正确调用,或者可能在会话超时后有效调用,这是 WEB.XML 中的一个参数(我的是 60 分钟)。这很奇怪,因为这是一个会话监听器,我的班级没有任何问题。

有人有线索吗?

package mybeans;

import entities.Users;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import jsf.util.JsfUtil;

/**
 * Session Listener.
 * @author TOTO
 */
@ManagedBean
public class SessionEar implements HttpSessionListener {

    public String ctext;
    File file = new File("sessionlog.csv");
    BufferedWriter output = null;
    public static int activesessions = 0;
    public static long creationTime = 0;
    public static int remTime = 0;
    String separator = ",";
    String headtext = "Session Creation Time" + separator + "Session Destruction Time" + separator + "User";

    /**
     * 
     * @return Remnant session time
     */
    public static int getRemTime() {
        return remTime;
    }

    /**
     * 
     * @return Session creation time
     */
    public static long getCreationTime() {
        return creationTime;
    }

    /**
     * 
     * @return System time
     */
    private String getTime() {
        return new Date(System.currentTimeMillis()).toString();
    }

    /**
     * 
     * @return active sessions number
     */
    public static int getActivesessions() {
        return activesessions;
    }

    @Override
    public void sessionCreated(HttpSessionEvent hse) {
        //  Insert value of remnant session time
        remTime = hse.getSession().getMaxInactiveInterval();

        // Insert value of  Session creation time (in seconds)
        creationTime = new Date(hse.getSession().getCreationTime()).getTime() / 1000;
        if (hse.getSession().isNew()) {
            activesessions++;
        } // Increment the session number
        System.out.println("Session Created at: " + getTime());
        // We write into a file information about the session created
        ctext = String.valueOf(new Date(hse.getSession().getCreationTime()) + separator);
        String userstring = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();

// If the file does not exist, create it
        try {
            if (!file.exists()) {
                file.createNewFile();

                output = new BufferedWriter(new FileWriter(file.getName(), true));
                // output.newLine();
                output.write(headtext);
                output.flush();
                output.close();
            }

            output = new BufferedWriter(new FileWriter(file.getName(), true));
            //output.newLine();
            output.write(ctext + userstring);
            output.flush();
            output.close();
        } catch (IOException ex) {
            Logger.getLogger(SessionEar.class.getName()).log(Level.SEVERE, null, ex);
            JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");
        }

        System.out.println("Session File has been written to sessionlog.txt");

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // Desincrement the active sessions number
            activesessions--;


        // Appen Infos about session destruction into CSV FILE
        String stext = "\n" + new Date(se.getSession().getCreationTime()) + separator;

        try {
            if (!file.exists()) {
                file.createNewFile();
                output = new BufferedWriter(new FileWriter(file.getName(), true));
                // output.newLine();
                output.write(headtext);
                output.flush();
                output.close();
            }
            output = new BufferedWriter(new FileWriter(file.getName(), true));
            // output.newLine();
            output.write(stext);
            output.flush();
            output.close();
        } catch (IOException ex) {
            Logger.getLogger(SessionEar.class.getName()).log(Level.SEVERE, null, ex);
            JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");
        }

    }
} // END OF CLASS

我以这种方式检索活动会话数:

<h:outputText id="sessionsfacet" value="#{UserBean.activeSessionsNumber}"/> 

从另一个托管Bean:

public String getActiveSessionsNumber() {
        return String.valueOf(SessionEar.getActivesessions());
    }

我的注销方法如下:

 public String logout() {
        HttpSession lsession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if (lsession != null) {
            lsession.invalidate();
        }
        JsfUtil.addSuccessMessage("You are now logged out.");
        return "Logout";
    }
    // end of logout
4

3 回答 3

10

我不确定。这似乎适用于单个访客。但是有些东西在你的HttpSessionListener.


@ManagedBean
public class SessionEar implements HttpSessionListener {

为什么是一个@ManagedBean?没有意义,删掉。在 Java EE 6 中,您将@WebListener改为使用。


    BufferedWriter output = null;

绝对不应该是一个实例变量。它不是线程安全的。将其声明为methodlocal。对于每个实现,在应用程序的整个生命周期中HttpSessionListener只有一个实例。当同时创建/销毁会话时,您output会在忙碌时被另一个会话覆盖,并且您的文件会损坏。


    public static long creationTime = 0;
    public static int remTime = 0;

这些也不应该是实例变量。每个新的会话创建都会覆盖它,它会反映到所有其他用户的演示中。即它不是线程安全的。如果您出于某种原因需要将其移到那里,请摆脱它们并在 EL 中使用#{session.creationTime}和。#{session.maxInactiveInterval}或者直接从HttpSessionHTTP 请求中的实例获取。


    if (hse.getSession().isNew()) {

这在方法内部总是正确的sessionCreated()。这是没有意义的。去掉它。


        JsfUtil.addErrorMessage(ex, "Cannot append session Info to File");

我不知道该方法到底在做什么,但我只想警告说,当会话即将被创建或销毁时,不能保证线程中存在。FacesContext它可能发生在非 JSF 请求中。或者可能根本没有 HTTP 请求。所以你冒着NPE的风险,因为那时FacesContext就是null这样。


尽管如此,我创建了以下测试片段,它对我来说很好。bean 隐式@SessionScoped创建会话。命令按钮使会话无效。所有方法都按预期调用。您在同一浏览器选项卡中还按下按钮多少次,计数始终为 1。

<h:form>
    <h:commandButton value="logout" action="#{bean.logout}" />
    <h:outputText value="#{bean.sessionCount}" />
</h:form>

@ManagedBean
@SessionScoped
public class Bean implements Serializable {

    public void logout() {
        System.out.println("logout action invoked");
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    }

    public int getSessionCount() {
        System.out.println("session count getter invoked");
        return SessionCounter.getCount();
    }

}

@WebListener
public class SessionCounter implements HttpSessionListener {

    private static int count;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("session created: " + event.getSession().getId());
        count++;
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.println("session destroyed: " + event.getSession().getId());
        count--;
    }

    public static int getCount() {
        return count;
    }

}

(注意 Java EE 5 你需要像往常一样注册<listener>web.xml

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

如果上面的示例对您有用,那么您的问题可能出在其他地方。也许您根本没有将其注册为<listener>in web.xml,而您只是在每次登录方法中手动创建侦听器的新实例。无论如何,现在您至少有一个最小的启动示例可以进一步构建。

于 2011-06-10T20:49:22.483 回答
3

完全不同的方向 - tomcat 支持 JMX。有一个 JMX MBean 会告诉您活动会话的数量。(如果你的容器不是 tomcat,它应该仍然支持 JMX 并提供一些方法来跟踪它)

于 2011-06-10T22:10:50.390 回答
1

你的public void sessionDestroyed(HttpSessionEvent se) {叫吗?我不明白为什么它不会增加。用户通过注销调用后session.invalidate(),会话被销毁,并为下一个请求创建一个新的。这是正常行为。

于 2011-06-10T20:45:38.417 回答