通过session统计当前在线人数
1
2
3
4
|
|
配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package
com.oracle.com;
import
javax.servlet.ServletContext;
import
javax.servlet.http.HttpSession;
import
javax.servlet.http.HttpSessionEvent;
import
javax.servlet.http.HttpSessionListener;
public
class
MyListener
implements
HttpSessionListener {
@Override
public
void
sessionCreated(HttpSessionEvent event) {
// System.out.println("创建了");
HttpSession session = event.getSession();
// 获得Session对象
// 通过Session获得servletcontext对象
ServletContext servletContext = session.getServletContext();
/**
* 1.获取num值
* 2.加1
* 3.存入servletcontext
*/
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 event) {
// System.out.println("销毁了");
HttpSession session = event.getSession();
// 获得Session对象
// 通过Session获得servletcontext对象
ServletContext servletContext = session.getServletContext();
/**
* 1.获取num值
* 2.减1
* 3.存入servletcontext
*/
servletContext.setAttribute(
"num"
, (
long
) servletContext.getAttribute(
"num"
) -
1
);
}
}
|
统计
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package
com.oracle.com;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpSession;
public
class
servletDemo5
extends
HttpServlet {
@Override
protected
void
doGet(HttpServletRequest req, HttpServletResponse resp)
throws
ServletException, IOException {
doPost(req, resp);
}
@Override
protected
void
doPost(HttpServletRequest req, HttpServletResponse resp)
throws
ServletException, IOException {
req.setCharacterEncoding(
"utf-8"
);
resp.setContentType(
"text/html;charset=utf-8"
);
HttpSession session = req.getSession();
// 创建Session
// session.setMaxInactiveInterval(10);//设置失效时间10秒 不是销毁
PrintWriter writer = resp.getWriter();
ServletContext servletContext = getServletContext();
Object num = servletContext.getAttribute(
"num"
);
writer.write(
"在线人数:"
+ num);
}
}
|