链接: https://pan.baidu.com/s/1-U-ayVaXgo9UUFVj1bO8qg 提取码: bhe6 复制这段内容后打开百度网盘手机App,操作更方便哦
一、效果图
使用多个浏览器打开模拟多用户登录
二、相关代码
人数访问监听
package
com.my.deal;
import
javax.servlet.ServletContext;
import
javax.servlet.http.HttpSession;
import
javax.servlet.http.HttpSessionEvent;
import
javax.servlet.http.HttpSessionListener;
public
class
ServletListener
implements
HttpSessionListener{
/**
* 创建
*/
@Override
public
void
sessionCreated(HttpSessionEvent se) {
HttpSession session=se.getSession();
ServletContext servletContext = session.getServletContext();
Object object = servletContext.getAttribute(
"num"
);
if
(object ==
null
) {
servletContext.setAttribute(
"num"
,
1
);
}
else
{
Object num = servletContext.getAttribute(
"num"
);
int
num1 = (
int
) num;
servletContext.setAttribute(
"num"
, num1 +
1
);
}
}
/**
* 销毁
*/
@Override
public
void
sessionDestroyed(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
servletContext.setAttribute(
"num"
, (
long
)servletContext.getAttribute(
"num"
)-
1
);
}
}
在web.xml中注册监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>ServletListener</listener-class>
</listener>
</web-app>