监听的定义

对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. hdu 3507 斜率dp

    不好理解,先多做几个再看 此题是很基础的斜率DP的入门题. 题意很清楚,就是输出序列a[n],每连续输出的费用是连续输出的数字和的平方加上常数M 让我们求这个费用的最小值. 设dp[i]表示输出前i个 ...

  2. 2016"百度之星" - 初赛(Astar Round2A)

    题目链接: http://bestcoder.hdu.edu.cn/contests/contest_show.php?cid=701 1001 : 矩阵快速幂 #include <iostre ...

  3. c# 作业1

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. Mosquitto关于Connection lost的问题。

    文章发自:http://www.cnblogs.com/hark0623/p/4175048.html  转发请注明 如果当你的客户端订阅(sub)mqtt时,发现出现Connection lost ...

  5. Android 编程下如何调整 SwipeRefreshLayout 的下拉刷新距离

    SwipeRefreshLayout 的下拉刷新距离比较短,并且也没有提供设置下拉距离的 API,但是看 SwipeRefreshLayout 的源码,会发现有一个内部变量 mDistanceToTr ...

  6. 递推DP URAL 1119 Metro

    题目传送门 /* 题意:已知起点(1,1),终点(n,m):从一个点水平或垂直走到相邻的点距离+1,还有k个抄近道的对角线+sqrt (2.0): 递推DP:仿照JayYe,处理的很巧妙,学习:) 好 ...

  7. NGif, Animated GIF Encoder for .NET

    1.简介 链接: http://www.codeproject.com/Articles/11505/NGif-Animated-GIF-Encoder-for-NET 2.代码使用 1)多个Imag ...

  8. Converting Stream to String and back…what are we missing?

    string test = "Testing 1-2-3"; // convert string to stream byte[] byteArray = Encoding.ASC ...

  9. BZOJ3680 : 吊打XXX

    本题就是找一个受力平衡的点 我们一开始假设这个点是(0,0) 然后求出它受到的力,将合力正交分解后朝着合力的方向走若干步,并不断缩小步长,一步步逼近答案 #include<cstdio> ...

  10. 数据库操作sql【转】

    Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname,T#) 课程表SC(S#,C#,score) 成绩表Teacher(T#,Tname) 教师表 问题:1. ...