一、简介

Listener是Servlet规范的另一个高级特性,它用于监听java web程序的事件,例如创建、修改、删除session,request,context等,并触发相应的处理事件,这个处理事件是由web容器回掉的。

学过安卓开发的同学一定很熟悉view.setonClickLister();这样的对安卓控件的监听。java web也是这样的 ,根据不同的listner 和不同的event,可以完成相应的处理事件。

二、Listerner的分类

Listerner分为八种,前三种是用于监听对象的创建和销毁,中间三种用于监听对象属性的变化,后两种用于监听Session内对象。

  • httpSessionListner: 监听session的创建与销毁,用于收集在线用户信息。

  • servletContextListener:监听context的创建与销毁,context代表当前web应用,该listener可用于启动时获取web.xml的初始化参数。

  • servletRequestListener: 监听request 的创建与销毁。

  • httpSessionAttributeListener 监听session的种属性变化

  • ServletContextAttributeListener

  • ServletRequestAttributeListener

  • HttpSessionBindingListener,监听对象存入或者移除 session

  • httpSessionActivationListener,钝化和重新加载 session的监听

三、监听session、request、servletContext

直接上代码,下面监听了这三个对象创建销毁。

public class ListenerTest implements HttpSessionListener ,ServletContextListener,ServletRequestListener{

	Log log=LogFactory.getLog(getClass());
public void requestDestroyed(ServletRequestEvent sre) {
HttpServletRequest request=(HttpServletRequest) sre.getServletRequest();
long time=System.currentTimeMillis()-(Long)request.getAttribute("time");
log.info("请求处理时间"+time); } public void requestInitialized(ServletRequestEvent sre) {
HttpServletRequest request=(HttpServletRequest) sre.getServletRequest();
String uri=request.getRequestURI();
uri=request.getQueryString()==null?uri:(uri+"?"+request.getQueryString());
log.info("ip"+request.getRemoteAddr()+uri);
request.setAttribute("time", System.currentTimeMillis()); } public void contextDestroyed(ServletContextEvent sce) {
ServletContext servletContext=sce.getServletContext();
log.info("关闭:"+servletContext.getContextPath()); } public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext=sce.getServletContext();
log.info("启动:"+servletContext.getContextPath()); } public void sessionCreated(HttpSessionEvent se) {
HttpSession session=se.getSession();
log.info("创建:session:"+session.getId()); } public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session=se.getSession();
log.info("销毁建:session:"+session.getId()); } }

需要在web.xml中配置:

 <listener>
<listener-class>com.forezp.listener.ListenerTest</listener-class>
</listener>

四、监听对象属性的变化

  • httpSessionAttributeListener 监听session的种属性变化
  • ServletContextAttributeListener
  • ServletRequestAttributeListener

以上三种方法用于监听session ,context,request的属性发生变化,例如添加、更新、移除。

下面以session的属性变化为例子:

public class SessionAttributeListener  implements HttpSessionAttributeListener{

	Log log=LogFactory.getLog(getClass());
public void attributeAdded(HttpSessionBindingEvent se) {
HttpSession httpSession=se.getSession();
log.info("新建属性:"+se.getName()+"值:"+se.getValue()); } public void attributeRemoved(HttpSessionBindingEvent se) {
HttpSession httpSession=se.getSession();
log.info(" 删除属性:"+se.getName()+"值:"+se.getValue()); } public void attributeReplaced(HttpSessionBindingEvent se) {
HttpSession httpSession=se.getSession();
log.info(" 修改属性:"+se.getName()+"原来的值:"+se.getValue()+"新值:"+httpSession.getAttribute(se.getName())); } }

web.xml配置,此处省略。

五、监听session内的对象

  • HttpSessionBindingListener,当对象被放到session里执行valueBond();当对象被移除,执行valueUnbond();
  • httpSessionActivationListener,服务器关闭,会将session的内容保存在硬盘里,这个过程叫钝化;服务器重启,会将session的内容从硬盘中重新加载。钝化时执行sesionWillPassivate(),重新加载sessionDidActivate();

举个例子:

public class User implements HttpSessionBindingListener,HttpSessionActivationListener,Serializable {

	private String username;
private String password; public void valueBound(HttpSessionBindingEvent httpsessionbindingevent) {
System.out.println("valueBound Name:"+httpsessionbindingevent.getName());
} public void valueUnbound(HttpSessionBindingEvent httpsessionbindingevent) {
System.out.println("valueUnbound Name:"+httpsessionbindingevent.getName());
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} //钝化
public void sessionWillPassivate(HttpSessionEvent httpsessionevent) {
System.out.println("sessionWillPassivate "+httpsessionevent.getSource());
}
//活化
public void sessionDidActivate(HttpSessionEvent httpsessionevent) {
System.out.println("sessionDidActivate "+httpsessionevent.getSource());
} }

init.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.getSession().setAttribute("currentUser", new com.forezp.entity.User()); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'init.jsp' starting page</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>
这是初始化值的界面
<button onclick="location.href='<%=request.getContextPath()%>/init.jsp';">Init</button>
<button onclick="location.href='<%=request.getContextPath()%>/destory.jsp';">Destory</button>
</body>
</html>

destroy.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; request.getSession().removeAttribute("currentUser");
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'destory.jsp' starting page</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>
这是销毁界面
<button onclick="location.href='<%=request.getContextPath()%>/init.jsp';">Init</button>
<button onclick="location.href='<%=request.getContextPath()%>/destory.jsp';">Destory</button>
</body>
</html>

当访问init.jsp,再访问destroy.jsp;再访问init,jsp,再关闭服务器,重启;log日志如下:

valueBound Name:currentUser

valueUnbound Name:currentUser

sessionWillPassivate org.apache.catalina.session.StandardSessionFacade@33f3be1

sessionDidActivate

org.apache.catalina.session.StandardSessionFacade@33f3be1

六、显示在线人数:


@WebListener
public class MyHttpSessionListener implements HttpSessionListener { private int userNumber = 0; @Override
public void sessionCreated(HttpSessionEvent arg0) {
userNumber++;
arg0.getSession().getServletContext().setAttribute("userNumber", userNumber);
} @Override
public void sessionDestroyed(HttpSessionEvent arg0) {
userNumber--;
arg0.getSession().getServletContext().setAttribute("userNumber", userNumber); } }

jsp中显示:


<body>
当前在线用户人数:${userNumber }<br/>
</body>

这是一个简答的统计在线人数的方法,如果你需要知道这些人来自哪里,需要配合httpRequestListener配合,也可以实现单登陆,在这里不写代码了。




扫码关注公众号有惊喜

(转载本站文章请注明作者和出处 方志朋的博客

web的监听器,你需要知道这些...的更多相关文章

  1. web 自定义监听器中设置加载系统相关的静态变量及属性

    直接上代码: 在src下新建一个StartListener 实现接口ServletContextListener,: /** * @Title:StartListener.java * @Packag ...

  2. Java Web(五) 监听器Listener

    监听器概述 在上一篇里介绍了过滤器Filter,而Listener是Servlet的另一个高级特性.Listener用于监听Java Web程序中的事件,例如创建,修改,删除Session,reque ...

  3. web.xml 监听器

    一.作用 Listener就是在application,session,request三个对象创建.销毁或者往其中添加修改删除属性时自动执行代码的功能组件. Listener是Servlet的监听器, ...

  4. 【java web】监听器listener

    一.简介 Java的监听器,也是系统级别的监听.监听器随web应用的启动而启动.Java的监听器在c/s模式里面经常用到,它会对特定的事件产生产生一个处理.监听在很多模式下用到,比如说观察者模式,就是 ...

  5. web上下文监听器ServletContextListener

    1 package com.liveyc.common.listener; import javax.servlet.ServletContextEvent; import javax.servlet ...

  6. 通过web.xml监听器启动main方法

    web.xml中添加要启动的类 <listener> <listener-class>server.NettyServer</listener-class> < ...

  7. Web中Listener的创建

    使用Listener只需要两个步骤: 定义Listener实现类. 通过Annotation或在web.xml文件中配置Listener 实现Listener类 监听不同Web事件的监听器不相同,常用 ...

  8. Servlet,过滤器,监听器,拦截器的区别

    1.过滤器 Servlet中的过滤器Filter是实现了javax.servlet.Filter接口的服务器端程序,主要的用途是过滤字符编码.做一些业务逻辑判断等.其工作原理是,只要你在web.xml ...

  9. 编程语言 : Java的动态Web解决方案泛谈

    文章概述 最近发现很久前一股脑地学习框架,发觉越发迷糊.知道了框架只是暂时的,重点是基础的技术.该文大篇幅回顾Servlet技术栈和简要的MVC框架. 至于为什么学J2EE,额,大家都用框架,可框架也 ...

随机推荐

  1. python 下载图片

    import requests from PIL import Image from io import BytesIO url = 'http://image2.buslive.cn/shp/upl ...

  2. checkbox多选、全选js效果

    //全选checkbox function allCheck() { //全选input var all = $("input[name='all']"); //全部的input ...

  3. 使用WindowsAPI播放PCM音频

    这一篇文章同上一篇<使用WindowsAPI获取录音音频>原理具有相似之处,不再详细介绍函数与结构体的参数 1. waveOutGetNumDevs 2. waveOutGetDevCap ...

  4. Neutron命令测试1

    Refer: http://wenku.baidu.com/link?url=DtrbhO0A393hg8kOWKX0XYuZtSC8Iu0occn8NF1pYcUwNzlaSq5qXCQoNEBDM ...

  5. (转)Linux命令之md5sum

    Linux命令之md5sum  原文:https://www.cnblogs.com/zhuxiaohou110908/p/5786893.html 1. 背景 在网络传输.设备之间转存.复制大文件等 ...

  6. python 常见的异常类型

    python标准异常异常名称 描述BaseException 所有异常的基类SystemExit 解释器请求退出KeyboardInterrupt 用户中断执行(通常是输入^C)Exception 常 ...

  7. mysql-proxy读写分离,负载均衡

    配置mysql-proxy,创建主配置文件 cd /usr/local/mysql-proxy mkdir lua #创建脚本存放目录 mkdir logs #创建日志目录 cp share/doc/ ...

  8. MongoDB Windows环境搭建

    简介 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为WEB应用提供可扩展的高性能数据存 ...

  9. linux常用安装命令(ubuntu)

    安装 net-tools 安装命令 sudo apt install net-tools 安装ssh sudo apt-get install openssh-server 查看是否安装成功 sudo ...

  10. [LeetCode]19. Remove Nth Node From End of List删除链表的倒数第N个节点

    Given a linked list, remove the n-th node from the end of list and return its head. Example: Given l ...