会话对象更改时通知HttpSessionEvent
,此事件的相应侦听器接口是HttpSessionListener
。
我们可以在这个事件上执行一些操作,例如:计数统计当前登录的用户,记录登录时间,注销时间等用户详细信息。
HttpSessionListener接口的方法
在HttpSessionListener
接口中声明了两种方法,这些方法必须由servlet程序员来实现,以执行某些操作。
public void sessionCreated(HttpSessionEvent e)
:在创建会话对象时被调用。public void sessionDestroyed(ServletContextEvent e)
:当会话无效时被调用。
HttpSessionEvent和HttpSessionListener统计当前登录用户数的示例
在这个例子中,实现对当前登录的用户进行统计。主要创建了以下几个代码文件:
- index.html:从用户处获取输入。
- MyListener.java:一个侦听器类,用于计算当前登录的用户数量,并将此信息作为属性存储在
ServletContext
对象中。 - First.java:一个创建会话并打印登录用户数量的Servlet类。
- Logout.java:一个使会话无效的Servlet类。
打开Eclipse,创建一个动态Web项目:HttpSessionEvent,其完整的目录结构如下所示 -
以下是这个项目中的几个主要的代码文件。
文件:index.html -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>统计在线用户数量</title>
</head>
<body>
<div style="font-align: center;">
<form action="first" method="post">
用户名:<input type="text" name="username" value="admin">密码:<input
type="password" name="password"><input
type="submit" value="登录" />
</form>
</div>
</body>
</html>
监听器文件:CountUserListener.java -
package com.yiibai;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class CountUserListener implements HttpSessionListener {
ServletContext ctx = null;
static int total = 0, current = 0;
public void sessionCreated(HttpSessionEvent e) {
total++;
current++;
ctx = e.getSession().getServletContext();
ctx.setAttribute("totalusers", total);
ctx.setAttribute("currentusers", current);
}
public void sessionDestroyed(HttpSessionEvent e) {
current--;
ctx.setAttribute("currentusers", current);
}
}
文件:First.java -
package com.yiibai;
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 FirstServlet extends HttpServlet {
// 显示用户数
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// retrieving data from ServletContext object
ServletContext ctx = getServletContext();
int t = (Integer) ctx.getAttribute("totalusers");
int c = (Integer) ctx.getAttribute("currentusers");
out.print("<br>用户总数: " + t);
out.print("<br>当前用户数: " + c);
out.print("<br><a href='logout'>注销</a>");
out.close();
}
// 执行用户登录
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String n = request.getParameter("username");
String password = request.getParameter("password");
// 假设输入密码为:123456时,此用户登录成功
if (password == null) {
password = "";
}
if (password.equals("123456")) {
out.print("您好, " + n);
HttpSession session = request.getSession();
session.setAttribute("uname", n);
} else {
out.print("登陆失败 ~");
}
// retrieving data from ServletContext object
ServletContext ctx = getServletContext();
int t = (Integer) ctx.getAttribute("totalusers");
int c = (Integer) ctx.getAttribute("currentusers");
out.print("<br>用户总数: " + t);
out.print("<br>当前用户数: " + c);
out.print("<br><a href='logout'>注销</a>");
out.close();
}
}
文件:LogoutServlet.java -
package com.yiibai;
import java.io.IOException;
import java.io.PrintWriter;
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 LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
session.invalidate();// invalidating session
out.print("You are successfully logged out");
out.close();
}
}
文件:web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>HttpSessionEvent</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.yiibai.CountUserListener</listener-class>
</listener>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.yiibai.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.yiibai.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>
在编写上面代码后,部署此Web应用程序(在项目名称上点击右键->”Run On Server…”),打开浏览器访问URL: http://localhost:8080/HttpSessionEvent/ ,如果没有错误,应该会看到以下结果 -
打开另一个浏览器访问URL: http://localhost:8080/HttpSessionEvent/ ,登录应用,然后注销,再次访问: http://localhost:8080/HttpSessionEvent/first ,应该看到以下结果 -