java - servlet中HttpSessionListener的变量共享问题
大家讲道理
大家讲道理 2017-04-18 10:19:40
0
2
602
package com.imooc.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener()
public class MyHttpListener implements HttpSessionListener {

    private int number = 0;

    public MyHttpListener() {
    }


    public void sessionCreated(HttpSessionEvent se) {
        number++;
        se.getSession().getServletContext().setAttribute("userNumber",number);
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        number--;
        se.getSession().getServletContext().setAttribute("userNumber",number);
    }

}

上面的代码是一个通过session统计在线人数的代码,可以正常使用
但是为什么number这个变量可以共享,难道不是每当一个人访问建立一个新的对象吗

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
Ty80

servlet, filter, listenerThey are all single instances.

伊谢尔伦

Session multi-threading problem. Cache cache is better for multi-threading, and there will be no problems such as parent-child threads.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!