一、简介

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 列表与元组的操作简介

    python 列表与元组的操作简介 原文:https://www.cnblogs.com/QG-whz/p/4782809.html 阅读目录 列表 list函数 列表的基本操作 列表方法 元组 tu ...

  2. (转)Python字典实现三级菜单

    Python字典实现三级菜单 原文:https://www.cnblogs.com/pyramid1001/p/5803294.html 1 ############################# ...

  3. 用信鸽来解释 HTTPS

    原文:http://blog.jobbole.com/113883/ ----------------------------------------------------------------- ...

  4. docker~service将容器日志输出到fluentd

    我们把微小的服务发布到docker里,然后实现docker service启动它,保证了服务的高可用性,然后把服务产生的日志输出到fluentd,由它进行过滤和转发,存储到elasticsearch里 ...

  5. type='button'和'submit'的区别

    今天在对表单的项目进行删除时出现了问题,原因就出现在点击input按钮时,这个input属性是type='button'还是type='submit'. 代码大致如下: <script type ...

  6. node搭环境(三)之安装vue-devtools

    前面已经安装了bower gulp,马上要学vue了,今天安装vue及调试神器vue-devtools 安装步骤: 1.在GitHub上输入 github.com/vuejs/vue-devtool后 ...

  7. hdu 4123 树形DP+单调队列

    http://acm.hust.edu.cn/vjudge/problem/25790 这题基本同poj 3162 要注意mx,mx2,vx,vx2每次都要初始化 #include <iostr ...

  8. 浏览器警告:provisional headers are shown

    做项目的时候遇到一个问题 后台JAVA,每次发送的都有一次拦截,去转发到登录页面的url 有一个请求是https的,被拦截后显示发生了错误,浏览器警告:provisional headers are ...

  9. Stimulsoft Reports送2年免费升级与技术支持

    慧都十年大促,与著名报表控件商Stimulsoft联合推出独家活动,即日起12月31日前,购买指定授权的Stimulsoft Reports除了获得本身1年的免费升级外,还加送2年免费升级与技术支持, ...

  10. 【起航计划 011】2015 起航计划 Android APIDemo的魔鬼步伐 10 App->Activity->Reorder Activities 后退栈 Intent FLAG

    Reorder Activities 示例有四个相关的Activitives: ReorderOnLaunch, ReorderTwo,ReorderThree, ReorderFour.其中Reor ...