博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet监听器——实现在线登录人数统计小例子
阅读量:4010 次
发布时间:2019-05-24

本文共 7348 字,大约阅读时间需要 24 分钟。

一、概念

servlet监听器的主要目的是给web应用增加事件处理机制,以便更好的监视和控制web应用的状态变化,从而在后台调用相应处理程序。

二、监听器的类型

1.根据监听对象的类型和范围,分为3

Request事件监听器

HttpSession事件监听器

ServletContext事件监听器

2.八个监听接口和六个监听事件

三、ServletContext监听

1.Application对象

application是ServletContext的实例,由JSP容器默认创建。Servlet中调用getServletContext()方法得到ServletContext的实例。

全局对象即Application范围的对象,初始化阶段的变量值在web.xml中,经由<context-param>元素所设定的变量,它的范围也是Application的范围

2.ServletContextListener接口

用于监听Web应用启动和销毁的事件,监听器类需要实现ServletContextListener接口。

该接口的主要方法;

void contextInitialized(ServletContextEvent se):通知正在接受的对象,应用程序已经被加载及初始化

void contextDestroyed(ServletContextEvent se):通知正在接受的对象,应用程序已经被销毁

ServletContextEvent的主要方法:ServletContext getServletContext():取得当前的ServletContext对象

3.ServletContextAttributeListener

用于监听Web应用属性改变的事件,包括增加、删除、修改属性。监听器类需要实现ServletContextAttributeListener接口

ServletContextAttributeListener接口的主要方法:

void attributeAdded(ServletContextAttributeEvent se):若有对象加入Application的范围,通知正在收听的对象。

void attributeRemoved(ServletContextAttributeEvent se):若有对象从Application范围移除,通知正在收听的对象。

void attributeReplaced(ServletContextAttributeEvent se):若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象

ServletContextAttributeEvent中的主要方法:

getName():返回属性名称

getValue()返回属性的值

四、HttpSession 会话监听

1.HttpSessionListener

主要方法:

sessionCreated(HttpSessionEvent se):session创建

sessionDestroyed(HttpSessionEvent se):session销毁

2.HttpSessionActivationListener:

监听器监听Http会话的情况

3.HttpSessionAttributeListener:

监听HttpSession中属性的操作

该接口的主要方法:

void attributeAdded(HttpSessionBindingEvent se):监听Http会话中的属性添加

void attributeRemoved(HttpSessionBindingEvent se):监听Http会话中的属性移除

void attributeReplaced(HttpSessionBindingEvent se):监听Http会话中的属性更改操作

4.HttpSessionBindingListener

监听Http会话中对象的绑定信息

getSession():获取session对象

getName():返回session增加、删除、或替换的属性名称

getValue():返回session增加、删除、或替换的属性值

五、ServletRequest监听

可以监听客户端的请求

1.ServletRequestListener接口

用于监听客户端的请求初始化和销毁事件,需要实现ServletRequestListener接口
接口中的方法:
requestInitialized(ServletRequestEvent):通知当前对象请求已经被加载及初始化
requestDestroyed(ServletRequestEvent):通知当前对象,请求已经被消除
ServletRequestEvent实例中的方法
getServletRequest():获取ServletRequest对象
getServletContext():获取ServletContext对象
2.ServletRequestAttributeListener
用于监听Web应用属性改变的事件,包括增加属性、删除属性、修改属性
接口方法:
void attributeAdded(ServletRequestAttributeEvent e):向Request对象添加新属性
void attributeRemoved(ServletRequestAttributeEvent e):从request对象中删除属性
void attributeReplaced(ServletRequestAttributeEvent e):替换对象中现有属性值
ServletRequestAttributeEvent中的主要方法:
getName():返回Request增加、删除、或替换的属性名称
getValue():返回Request增加、删除、或替换的属性的值

六、存储在线用户信息的例子

1.login.jsp页面实现用户登录

	

用户登录


用户名:

2.建立存储用户信息的类:UserList.java

package listener;import java.util.Vector;public class UserList {	private static Vector online = new Vector();	//添加在线人数	public static void addUser(String userName){		online.addElement(userName);	}	//移除在线人数	public static void removeUser(String userName){		online.removeElement(userName);	}	//获取在线用户数量	public static int getUserCount(){		return online.size();	}	public static Vector getVector(){		return online;	}}
****Vector 类提供了实现可增长数组的功能,随着更多元素加入其中,数组变的更大。在删除一些元素之后,数组变小。 

Vector 有三个构造函数, 
public Vector(int initialCapacity,int capacityIncrement)  

public Vector(int initialCapacity)

public Vector()   

Vector 运行时创建一个初始的存储容量initialCapacity,存储容量是以capacityIncrement 变量定义的增量增长。初始的存储容量和capacityIncrement 可以在Vector 的构造函数中定义。第二个构造函数只创建初始存储容量。第三个构造函数既不指定初始的存储容量也不指定capacityIncrement。   

Vector 类提供的访问方法支持类似数组运算和与Vector 大小相关的运算。类似数组的运算允许向量中增加,删除和插入元素。

****

3.写监听器类

package listener;import javax.servlet.http.HttpSessionAttributeListener;import javax.servlet.http.HttpSessionBindingEvent;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class OnlineListener implements HttpSessionListener,HttpSessionAttributeListener{	//监听Http会话中的属性添加	public void attributeAdded(HttpSessionBindingEvent se) {		// TODO Auto-generated method stub		UserList.addUser(String.valueOf(se.getValue()));//增加一个用户		System.out.println("session("+se.getSession().getId()+")增加属性"+se.getName()+",值为"+se.getValue());	}	//监听Http会话中的属性移除	public void attributeRemoved(HttpSessionBindingEvent se) {		// TODO Auto-generated method stub		UserList.removeUser(String.valueOf(se.getValue()));		System.out.println(se.getValue()+"属性已移除");	}	//监听Http会话中的属性更改操作	public void attributeReplaced(HttpSessionBindingEvent se) {		// TODO Auto-generated method stub		String oldValue=String.valueOf(se.getValue());//旧的属性		String newValue=String.valueOf(se.getSession().getAttribute(se.getName()));//新的属性		UserList.removeUser(oldValue);//移除旧的属性		UserList.addUser(newValue);//增加新的属性		System.out.println(oldValue+"属性已更改为"+newValue);	}	public void sessionCreated(HttpSessionEvent se) {		// TODO Auto-generated method stub		System.out.println("会话已创建!");	}	public void sessionDestroyed(HttpSessionEvent se) {		// TODO Auto-generated method stub		System.out.println("会话已销毁!");	}}

4.建立用户登录类LoginServlet.java

package listener;import java.io.IOException;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 LoginServlet extends HttpServlet{	@Override	protected void doGet(HttpServletRequest req, HttpServletResponse resp)			throws ServletException, IOException {		// TODO Auto-generated method stub		String userName=req.getParameter("userName");//获取前台传来的userName属性		HttpSession session = req.getSession();		session.setAttribute("userName", userName);//将属性保存到session会话中		resp.sendRedirect("index.jsp");//重定向到index.jsp页面	}	@Override	protected void doPost(HttpServletRequest req, HttpServletResponse resp)			throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(req, resp);	}}

5.建立退出登录类

package listener;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ExitServlet extends HttpServlet{	@Override	protected void doGet(HttpServletRequest req, HttpServletResponse resp)			throws ServletException, IOException {		// TODO Auto-generated method stub		req.getSession().removeAttribute("userName");//从session中移除对象		resp.sendRedirect("login.jsp");//重定向到用户登录页面	}	@Override	protected void doPost(HttpServletRequest req, HttpServletResponse resp)			throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(req, resp);	}}

6.在web.xml中配置监听器、登录和退出的Servlet

listener.OnlineListener
LoginServlet
listener.LoginServlet
ExitServlet
listener.ExitServlet
LoginServlet
/logindo
ExitServlet
/exitdo

7.编写index.jsp在线首页

	<%		//如果未登录,转向登录页面		if (session.getAttribute("userName") == null) {			response.sendRedirect("login.jsp");		}		Vector onlineUsers = UserList.getVector(); //获取存储在线用户名的vector对象	%>	

登录成功


欢迎你
<%=session.getAttribute("userName")%>     
退出登录
当前在线人数:
<%=UserList.getUserCount()%>人
在线用户名单 :

你可能感兴趣的文章
技术栈
查看>>
Jenkins中shell-script执行报错sh: line 2: npm: command not found
查看>>
8.X版本的node打包时,gulp命令报错 require.extensions.hasownproperty
查看>>
Jenkins 启动命令
查看>>
Maven项目版本继承 – 我必须指定父版本?
查看>>
Maven跳过单元测试的两种方式
查看>>
通过C++反射实现C++与任意脚本(lua、js等)的交互(二)
查看>>
利用清华镜像站解决pip超时问题
查看>>
[leetcode BY python]1两数之和
查看>>
微信小程序开发全线记录
查看>>
Centos import torchvision 出现 No module named ‘_lzma‘
查看>>
网页设计里的浮动 属性
查看>>
Maximum Subsequence Sum
查看>>
PTA:一元多项式的加乘运算
查看>>
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
Django 的Error: [Errno 10013]错误
查看>>