JavaWeb应用中,很多的地方都和session有关。因此session相关的事件监听器,在日常工作中非常有用。
有时候我们需要统计当前在线的人数和访问人数总数,此时就可以使用监听器技术来很简单的实现这种功能。
注意:
session并不是浏览器关闭时销毁的,而是在session失效的时候销毁下列代码就是监测session创建、销毁。
销毁session,可以设置过期时间:
1
步骤说明
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"?>
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">
com.listener.InitNumListener
com.listener.UserEnterListener
1
BookList
com.control.BookList
BookList
/BookList
BookAdd
com.control.BookAdd
BookAdd
/BookAdd
BookUpdate
com.control.BookUpdate
BookUpdate
/BookUpdate
BookDoUpdate
com.control.BookDoUpdate
BookDoUpdate
/BookDoUpdate
BookDelete
com.control.BookDelete
BookDelete
/BookDelete
BookDoDelete
com.control.BookDoDelete
BookDoDelete
/BookDoDelete
BookBatchAdd
com.control.BookBatchAdd
BookBatchAdd
/BookBatchAdd
BookBatchDelete
com.control.BookBatchDelete
BookBatchDelete
/BookBatchDelete
BookFind
com.control.BookFind
BookFind
/BookFind
Login
com.control.Login
Login
/Login
DrawImage
com.control.DrawImage
DrawImage
/DrawImage
Register
com.control.Register
Register
/Register
LoginUser
com.control.LoginUser
LoginUser
/LoginUser
ExitLogin
com.control.ExitLogin
ExitLogin
/ExitLogin
Upload
com.control.Upload
Upload
/Upload
ListFile
com.control.ListFile
ListFile
/ListFile
Download
com.control.Download
Download
/Download
CharSetFilter
com.Filter.CharSetFilter
charset
UTF-8
CharSetFilter
/*
404
/error/error404.jsp
500
/error/error500.jsp
ErrorFilter
com.Filter.ErrorFilter
ErrorFilter
/error.jsp
ERROR
四.listen.jsp
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
Listen访问人数:${totalcount} 在线人数:${accesscount}
五.count.txt(总访问人数19)
六.页面效果
另一个浏览器(模拟多个用户)
关闭浏览器(模拟在线人数退出),等1-2分钟刷新
ok!