监听的定义

对application的监听

application是servletContext接口的对象,表示的是整个上下文环境,如果要想实现对application监听则可以使用如下两个接口:

servletContextListener:是对整个上下文环境的监听

servletContextAttrubiteListener:是对属性的监听。

import javax.servlet.* ;
public class ServletContextListenerDemo implements ServletContextListener {
public void contextInitialized(ServletContextEvent event){
System.out.println("** 容器初始化 --> " + event.getServletContext().getContextPath()) ;
}
public void contextDestroyed(ServletContextEvent event){
System.out.println("** 容器销毁 --> " + event.getServletContext().getContextPath()) ;
try{
Thread.sleep(300) ;
}catch(Exception e){}
}
}

在web.xml中配置<listener>

如果在web.xml中有servlet、filter、listener,则配置顺序如下

<filter>

<filter-mapping>

<listener>

<servlet>

<servlet-mapping>

使用servletContextAttributeListener操作属性

import javax.servlet.* ;
public class ServletContextAttributeListenerDemo implements ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent scab){
System.out.println("** 增加属性 --> 属性名称:" + scab.getName() + ",属性内容:" + scab.getValue()) ;
}
public void attributeRemoved(ServletContextAttributeEvent scab){
System.out.println("** 删除属性 --> 属性名称:" + scab.getName() + ",属性内容:" + scab.getValue()) ;
}
public void attributeReplaced(ServletContextAttributeEvent scab){
System.out.println("** 替换属性 --> 属性名称:" + scab.getName() + ",属性内容:" + scab.getValue()) ;
}
}

web.xml中配置

<listener>
<listener-class>
org.lxh.listenerdemo.ServletContextAttributeListenerDemo
</listener-class>
</listener>

  jsp中显示:

<%
request.setAttribute("info","www.MLDNJAVA.cn") ;
%>

  对session的监听

注意:session是属于http协议范畴,所以这些接口是在javax.servlet.http中定义的。

在servlet中,要想取得session依靠的是httpServletRequest接口中的getSession()方法。

import javax.servlet.http.* ;
public class HttpSessionListenerDemo implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se){
System.out.println("** SESSION创建,SESSION ID = " +se.getSession().getId() ) ;
}
public void sessionDestroyed(HttpSessionEvent se){
System.out.println("** SESSION销毁,SESSION ID = " +se.getSession().getId() ) ;
}
}

之后进行web.xml配置,启动服务器

当客户端第一次连接到服务器时,服务器会自动为用户创建一个session,同时分配一个sessionId。

session已经被创建,在第一次访问时触发事件,但什么时候被注销?

如果要想session被注销,有两种方法,但这两种方法都不是关闭页面可以实现的。

方法1:session注销---invaldate();

方法2:超时时间设置——在tomcat中一般时间设置为30min,也可以自己在web.xml中修改

<%    // 手工注销
session.invalidate() ;
%>

当调用invalidate()方法时session就被销毁了。

当然,时间越长,占用内存越大。

web.xml中设置

<session-config>
<session-timeout>1</session-timeout>
</session-config>

对session中的属性进行监听

import javax.servlet.http.* ;
public class HttpSessionAttributeListenerDemo implements HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent se){
System.out.println(se.getSession().getId() + ",增加属性 --> 属性名称" + se.getName() + ",属性内容:" + se.getValue()) ;
}
public void attributeRemoved(HttpSessionBindingEvent se){
System.out.println(se.getSession().getId() + ",删除属性 --> 属性名称" + se.getName() + ",属性内容:" + se.getValue()) ;
}
public void attributeReplaced(HttpSessionBindingEvent se){
System.out.println(se.getSession().getId() + ",替换属性 --> 属性名称" + se.getName() + ",属性内容:" + se.getValue()) ;
}
}
<%
session.setAttribute("info","www.MLDNJAVA.cn") ;
%>

到此为止,都与servletContext非常相似,之前所有的的监听都要在web.xml中进行配置,但是在session中有一个HttpSessionBindingListener也是实现监听的接口,但是这个接口不需要配置,可以直接使用。

import javax.servlet.http.* ;
public class LoginUser implements HttpSessionBindingListener {
private String name ;
public LoginUser(String name){
this.setName(name) ;
}
public void valueBound(HttpSessionBindingEvent event){
System.out.println("** 在session中保存LoginUser对象(name = " + this.getName() + "),session id = " + event.getSession().getId()) ;
}
public void valueUnbound(HttpSessionBindingEvent event){
System.out.println("** 从session中移出LoginUser对象(name = " + this.getName() + "),session id = " + event.getSession().getId()) ;
}
public String getName(){
return this.name ;
}
public void setName(String name){
this.name = name ;
}
}

此时不需要配置web.xml,但是jsp中就比较麻烦。

<%
LoginUser user = new LoginUser("MLDN") ;
session.setAttribute("info",user) ; // 直接保存LoginUser对象
%>

对request监听

import javax.servlet.* ;
public class ServletRequestListenerDemo implements ServletRequestListener {
public void requestInitialized(ServletRequestEvent sre){
System.out.println("** request初始化。http://" +
sre.getServletRequest().getRemoteAddr() +
sre.getServletContext().getContextPath()) ;
}
public void requestDestroyed(ServletRequestEvent sre){
System.out.println("** request销毁。http://" +
sre.getServletRequest().getRemoteAddr() +
sre.getServletContext().getContextPath()) ;
}
}

在web.xml中进行配置

<listener>
<listener-class>
org.lxh.listenerdemo.ServletRequestListenerDemo
</listen

对request中属性操作

import javax.servlet.* ;
public class ServletRequestAttributeListenerDemo implements ServletRequestAttributeListener {
public void attributeAdded(ServletRequestAttributeEvent srae){
System.out.println("** 增加request属性 --> 属性名称:" + srae.getName() + ",属性内容:" + srae.getValue()) ;
}
public void attributeRemoved(ServletRequestAttributeEvent srae){
System.out.println("** 删除request属性 --> 属性名称:" + srae.getName() + ",属性内容:" + srae.getValue()) ;
}
public void attributeReplaced(ServletRequestAttributeEvent srae){
System.out.println("** 替换request属性 --> 属性名称:" + srae.getName() + ",属性内容:" + srae.getValue()) ;
}
}

从实际来说,对request监听用的不多,用的最多的是对servletContext 和httpSession的监听。

监听实例

import java.util.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class OnlineUserList implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener {
private ServletContext app = null ;
public void contextInitialized(ServletContextEvent sce){
this.app = sce.getServletContext() ;
this.app.setAttribute("online",new TreeSet()) ; // 准备集合
}
public void contextDestroyed(ServletContextEvent sce){
}
public void attributeAdded(HttpSessionBindingEvent se){
Set all = (Set) this.app.getAttribute("online") ;
all.add(se.getValue()) ;
this.app.setAttribute("online",all) ;
}
public void attributeRemoved(HttpSessionBindingEvent se){
Set all = (Set) this.app.getAttribute("online") ;
all.remove(se.getSession().getAttribute("userid")) ;
this.app.setAttribute("online",all) ;
}
public void attributeReplaced(HttpSessionBindingEvent se){}
public void sessionCreated(HttpSessionEvent se){}
public void sessionDestroyed(HttpSessionEvent se){
Set all = (Set) this.app.getAttribute("online") ;
all.remove(se.getSession().getAttribute("userid")) ;
this.app.setAttribute("online",all) ;
} }
<form action="login.jsp" method="post">
用户ID:<input type="text" name="userid">
<input type="submit" value="登陆">
</form>
<%
String userid = request.getParameter("userid") ;
if(!(userid==null || "".equals(userid))){
session.setAttribute("userid",userid) ;
response.sendRedirect("list.jsp") ;
}
%>
<%
Set all = (Set) this.getServletContext().getAttribute("online") ;
Iterator iter = all.iterator() ;
while(iter.hasNext()){
%>
<h3><%=iter.next()%></h3>
<%
}
%>

javaWeb中servlet开发——监听器的更多相关文章

  1. javaWeb中servlet开发——过滤器

    servlet开发--过滤器(filter) servlet有三种,分为简单servlet.过滤器servlet.监听servlet 简单servlet是作为一种程序所必须的开发结构保存的,继承htt ...

  2. javaWeb中servlet开发(5)——WEB开发模式:Mode I与Mode II

    1.servlet开发 2.model I模式 客户端通过访问JSP,调用里面的javabean,而通过javabean调用处理数据库的操作,javabean中有专门处理数据库的操作,数据库主要以DA ...

  3. javaWeb中servlet开发(4)——servlet跳转

    servlet跳转 1.跳转类型 客户端跳转:跳转后地址栏改变,无法传递request范围内属性,是在所有的操作都执行完毕之后才发生跳转的操作,跳转语法是,response.sendRedict() ...

  4. javaWeb中servlet开发(3)——Servlet生命周期

    生命周期:是一个程序的存在周期,servlet由于是受容器的管理,所以容器来决定其生命周期 1.servlet生命周期 2.servlet生命周期对应的方法 3.servlet生命周期代码 publi ...

  5. javaWeb中servlet开发(2)——servlet与表单

    1.重写doGet方法 public class InputServlet extends HttpServlet{ public void doGet(HttpServletRequest req, ...

  6. javaWeb中servlet开发(1)——helloworld

    1.servlet 1.1 servlet简介 1.2 servlet流程 不管是servlet还是jsp,所有的程序都是在服务器端处理的,所以必须了解一个servlet基本流程 servlet和JS ...

  7. javaweb(五)——Servlet开发(一)

    一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...

  8. JavaWeb中servlet读取配置文件的方式

    我们在JavaWeb中常常要涉及到一些文件的操作,比如读取配置文件,下载图片等等操作.那我们能不能采用我们以前在Java工程中读取文件的方式呢?废话不多说我们来看看下我们以前在Java工程中读取文件是 ...

  9. javaweb(六)——Servlet开发(二)

    一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些 ...

随机推荐

  1. [原]ASP.NET 数据库访问通用工具

    在工作中,有很多项目已上线后,很多项目的数据库服务器都不会对外开放的,外网想直接访问客户数据库服务器时,可能会出现困难. 这时就需要一个可以查询,更新数据库操作的页面了: 本来用sql语句直接操作数据 ...

  2. Java Hour 23 Networking

    有句名言,叫做10000小时成为某一个领域的专家.姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧. 首先拟好主题,做到心中有数,再去写内容. socket public stat ...

  3. VMware安装、配置CentOS

    出处:http://www.cnblogs.com/jlily/ 1. 准备CentOS安装镜像文件 官网下载地址:http://www.centos.org/download/ 官方有三个版本:DV ...

  4. VS制作软件安装项目,版本控制和软件升级

    具体如何利用VS制作安装项目,请到我的CSDN地址下载超详细的文档(该文档来自网络) http://download.csdn.net/detail/u012373717/8723335 我要说的是版 ...

  5. error opening trace file: No such file or directory (2) ,can't load transform_config.xml

    出现这个错误:error opening trace file: No such file or directory (2) ,can't load transform_config.xml 是因为没 ...

  6. iOS Simulator功能介绍关于Xamarin IOS开发

    iOS Simulator功能介绍关于Xamarin IOS开发 iOS Simulator功能介绍 在图1.38所示的运行效果中,所见到的类似于手机的模型就是iOS Simulator.在没有iPh ...

  7. 贪心 Gym 100502E Opening Ceremony

    题目传送门 /* 题意:有一堆砖块,每一次操作可以选择消去任意一行,也可以选择消去任意一列.求要消去所有的砖块需要最小的操作数 贪心:首先清楚的是消去最高列的最佳,消去第一行最佳,行列的顺序只对中间过 ...

  8. fork和execve

    fork函数在新的子进程中运行相同的程序,新的子进程是父进程的一个复制品. execve函数在当前进程的上下文中加载并运行一个新的程序.它会覆盖当前进程的地址空间,但并没有创建一个新的进程.新的程序仍 ...

  9. 【BZOJ】3196: Tyvj 1730 二逼平衡树(区间第k小+树套树)

    http://www.lydsy.com/JudgeOnline/problem.php?id=3196 Treap+树状数组 1WA1A,好伤心,本来是可以直接1A的,这次开始我并没有看题解,就写出 ...

  10. SVN组成中trunk,branches and tags功能用法详解

    SVN组成中trunk,branches and tags功能用法详解  我相信初学开发在SVN作为版本管理时,都估计没可能考虑到如何灵活的运用SVN来管理开发代码的版本,下面我就摘录一篇文章来简单说 ...