JavaWeb应用中,很多的地方都和session有关。因此session相关的事件监听器,在日常工作中非常有用。
有时候我们需要统计当前在线的人数和访问人数总数,此时就可以使用监听器技术来很简单的实现这种功能。
注意:
session并不是浏览器关闭时销毁的,而是在session失效的时候销毁下列代码就是监测session创建、销毁。
销毁session,可以设置过期时间:
<!--session过期时间为1分钟 0为不过期-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
步骤说明
1、代码请参考——第十五篇JDBC操作数据库之Cookie技术。2、在第十五篇基础上继续实现功能——第十六篇JDBC操作数据库之监听器。
一.InitNumListener.java
对ServletContext对象进行监听的接口有ServletContextAttributeListener 和 ServletContext-Listener。
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.*;
/**
* Created by Ray on 2018/3/17 0017.
**/
public class InitNumListener implements ServletContextListener {
//初始化上下文
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
//创建接口
ServletContext servletContext = sce.getServletContext();
//访问总数的文件路径
String filename = servletContext.getRealPath("/WEB-INF/count.txt");
File file = new File(filename);
//初始化访问总数
Integer totalcount = 0;
if(file.exists()){
try{
//读取文件内容
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
totalcount = Integer.valueOf(bufferedReader.readLine());
//关闭流
bufferedReader.close();
fileReader.close();
}catch (Exception e){
e.printStackTrace();
}
}
//设置属性name的值为value
servletContext.setAttribute("totalcount",totalcount); //访问总数
servletContext.setAttribute("accesscount",0); //在线用户数
}
//销毁上下文
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
//创建接口
ServletContext servletContext = sce.getServletContext();
//访问总数的文件路径
String filename = servletContext.getRealPath("/WEB-INF/count.txt");
File file = new File(filename);
try{
//将内容写入文件
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(servletContext.getAttribute("totalcount").toString());
//关闭流
bufferedWriter.close();
fileWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
二.UserEnterListener.java
实现HttpSessionListener接口的监听器,可以监听 HttpSession 对象本身的创建和销毁。
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Created by Ray on 2018/3/17 0017.
**/
public class UserEnterListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
ServletContext servletContext = se.getSession().getServletContext();
//返回属性name的值
Integer totalcount = (Integer) servletContext.getAttribute("totalcount");
Integer accesscount = (Integer) servletContext.getAttribute("accesscount");
//使用指定的属性名字绑定一个对象并储存到session中
servletContext.setAttribute("totalcount",totalcount+1);
servletContext.setAttribute("accesscount",accesscount+1);
}
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
ServletContext servletContext = se.getSession().getServletContext();
//返回属性name的值
Integer accesscount = (Integer) servletContext.getAttribute("accesscount");
//使用指定的属性名字绑定一个对象并储存到session中
servletContext.setAttribute("accesscount",accesscount-1);
}
}
三.web.xml
1.监听器Listener
2.设置session过期时间
3.省略部分代码(懒得删)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--监听器Listener-->
<listener>
<listener-class>com.listener.InitNumListener</listener-class>
</listener>
<listener>
<listener-class>com.listener.UserEnterListener</listener-class>
</listener>
<!--session过期时间为1分钟 0为不过期-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<servlet>
<servlet-name>BookList</servlet-name>
<servlet-class>com.control.BookList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookList</servlet-name>
<url-pattern>/BookList</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookAdd</servlet-name>
<servlet-class>com.control.BookAdd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookAdd</servlet-name>
<url-pattern>/BookAdd</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookUpdate</servlet-name>
<servlet-class>com.control.BookUpdate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookUpdate</servlet-name>
<url-pattern>/BookUpdate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookDoUpdate</servlet-name>
<servlet-class>com.control.BookDoUpdate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookDoUpdate</servlet-name>
<url-pattern>/BookDoUpdate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookDelete</servlet-name>
<servlet-class>com.control.BookDelete</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookDelete</servlet-name>
<url-pattern>/BookDelete</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookDoDelete</servlet-name>
<servlet-class>com.control.BookDoDelete</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookDoDelete</servlet-name>
<url-pattern>/BookDoDelete</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookBatchAdd</servlet-name>
<servlet-class>com.control.BookBatchAdd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookBatchAdd</servlet-name>
<url-pattern>/BookBatchAdd</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookBatchDelete</servlet-name>
<servlet-class>com.control.BookBatchDelete</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookBatchDelete</servlet-name>
<url-pattern>/BookBatchDelete</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookFind</servlet-name>
<servlet-class>com.control.BookFind</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookFind</servlet-name>
<url-pattern>/BookFind</url-pattern>
</servlet-mapping>
<!--验证码功能-->
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.control.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DrawImage</servlet-name>
<servlet-class>com.control.DrawImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DrawImage</servlet-name>
<url-pattern>/DrawImage</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>com.control.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginUser</servlet-name>
<servlet-class>com.control.LoginUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginUser</servlet-name>
<url-pattern>/LoginUser</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ExitLogin</servlet-name>
<servlet-class>com.control.ExitLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExitLogin</servlet-name>
<url-pattern>/ExitLogin</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.control.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ListFile</servlet-name>
<servlet-class>com.control.ListFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListFile</servlet-name>
<url-pattern>/ListFile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Download</servlet-name>
<servlet-class>com.control.Download</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Download</servlet-name>
<url-pattern>/Download</url-pattern>
</servlet-mapping>
<!--登录拦截-->
<!--<filter>-->
<!--<filter-name>LoginFilter</filter-name>-->
<!--<filter-class>com.Filter.LoginFilter</filter-class>-->
<!--<init-param>-->
<!--<param-name>noLoginPaths</param-name>-->
<!--<param-value>registerUser.jsp;bookList.css;userStyle.css;loginSql.jsp;login.jsp;fail.jsp;Login;ErrorFilter;DrawImage</param-value>-->
<!--</init-param>-->
<!--</filter>-->
<!--<filter-mapping>-->
<!--<filter-name>LoginFilter</filter-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</filter-mapping>-->
<!--配置过滤器-->
<filter>
<filter-name>CharSetFilter</filter-name>
<filter-class>com.Filter.CharSetFilter</filter-class>
<init-param>
<!--用来指定一个具体的字符集-->
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!--映射过滤器-->
<filter-mapping>
<filter-name>CharSetFilter</filter-name>
<!--“/*”表示拦截所有的请求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--拦截404,500页面-->
<error-page>
<error-code>404</error-code>
<location>/error/error404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
<filter>
<filter-name>ErrorFilter</filter-name>
<filter-class>com.Filter.ErrorFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ErrorFilter</filter-name>
<url-pattern>/error.jsp</url-pattern>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
</web-app>
四.listen.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Listen</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h2>访问人数:${totalcount} 在线人数:${accesscount}</h2>
</body>
</html>
五.count.txt(总访问人数19)
六.页面效果
另一个浏览器(模拟多个用户)
关闭浏览器(模拟在线人数退出),等1-2分钟刷新
ok!