作用域对象
Servlet上下文监听器
Servlet会话监听器
Servlet请求监听器
 
 
一:对象作用域

作用域对象

属性操作方法

作用域范围说明

ServletContext(上下文)

void setAttribute(String, Object)

Object getAttribute(Sting)

void removeAttribute(String)

Enumeration getAttributeNames()

整个Web应用程序

HttpSession(会话)

一个会话交互过程

ServletRequest(请求)

一次请求过程

1.1ServletContext应用上下文

例子:页面访问量的统计程序
主要的代码块:
         ServletContext sc=getServletContext();
Integer count=(Integer)sc.getAttribute("counter");
if(count==null){
count=new Integer(1);
}else{
count=new Integer(count.intValue()+1);
}
sc.setAttribute("counter", count);
resp.getWriter().print("该页面被访问的次数是:"+count);
resp.getWriter().close();

提示:上下文作用域中设置的属性在整个Web应用中被共享,只要服务器不被关闭,Web应用中任何一部分都能访问到该属性。所以线程是不安全的。

1.2 HttpSession 会话作用域

例子:在线多人登录

主要的代码块:

count

 1         PrintWriter pw=resp.getWriter();
ServletContext sc=getServletContext();
HttpSession sess=req.getSession();
String name = req.getParameter("username");
List<String> userList=(List) getServletContext().getAttribute("userList");
if(userList==null){
userList=new ArrayList<String>();
}
if(name!=null){
name=new String(name.getBytes("iso-8859-1"),"utf-8");
System.out.println("================="+name);
userList.add(name);
sess.setAttribute("username",name);
getServletContext().setAttribute("userList", userList);
req.getRequestDispatcher("/count1").forward(req, resp); }
else{
pw.print("<html>");
pw.print("<head></head>");
pw.print("<body><h1>在线书店登录</h1>");
pw.print("<form action='/day13/count'>");
pw.print("username:<input type='text' name='username'/><br/>");
pw.print("<input type='submit' value='submit'/></form></body>");
pw.print("</html>");
}
pw.flush();
pw.close();

count1

  PrintWriter pw=resp.getWriter();
HttpSession sess=req.getSession();
List<String> userList=(List) getServletContext().getAttribute("userList");
String name=(String) sess.getAttribute("username");
String action=req.getParameter("action");
if(action==null){
pw.print("用户"+name+"欢迎你!【<a href='count1?action=loginout'>注销</a>】<br/>");
Iterator<String> i=userList.iterator();
while(i.hasNext()){
String name1=i.next();
pw.print("<p>当前用户有:"+name1+"</p>");
} }else if(action.equals("loginout")){
sess.invalidate();
userList.remove(name);
getServletContext().setAttribute("userList", userList); }
    
 
提示:每一个会话只能访问当前会话作用域中设置的属性。但是当我们使用特殊的浏览器窗口打开方式使用相同的Session来访问该设置的属性。也就是说多个线程访问相同的会话属性。所以线程也是不安全的。
 
1.3  ServletRequest 请求作用域
系统的资源消耗

属性可以保存在请求作用域范围中

 
 
 
二:监听器概述
监听session,request,application这三个对象里存取数据的变化
监听器对象可以在事情发生前、发生后可以做一些必要的处理
Servlet监听器主要目的是给Web应用增加事件处理机制,以便更好地监视和控制Web应用的状态变化
      Servlet监听器接口和相对应的监听器事件类

事件类型

描述

Listener接口

ServletContext   事件

生命周期

Servlet上下文刚被创建并可以开始为第一次请求服务,或者Servlet上下文将要被关闭发生的事件

ServletContextListener

属性改变

Servlet上下文内的属性被增加、删除或者替换时发生的事件

ServletContextAttributeListener

HttpSession    事件

生命周期

HttpSession被创建、无效或超时时发生

HttpSessionListener

HttpSessionActivationListener

会话迁移

HttpSession被激活或钝化时发生

属性改变

在HttpSession中的属性被增加、删除、替换时发生

HttpSessionAttributeListener

HttpSessionBindingListener

对象绑定

对象被绑定到或者移出HttpSession时发生。

ServletRequest   事件

生命周期

在Servletr请求开始被Web组件处理时发生

ServletRequestListener

属性改变

在ServletRequest对象中的属性被增加、删除、替换时发生

ServletRequestAttributeListener

三:监听Web应用程序范围内的事件

Web应用启动和销毁事件
Web应用程序的属性发生改变的事件(包括增加、删除、修改)。
定义了ServletContextListener和ServletContextAttributeListener两个接口

监听器需要在web.xml定义监听器:

<listener>
         <listener-class>com.cy.listener.servletContext</listener-class>
</listener>

1)ServletContextListener接口的方法如下:
例子:由监听器管理共享数据库连接
 package com.cy.listener;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class ServletContext implements ServletContextListener { @Override
public void contextDestroyed(ServletContextEvent arg0) {
//应用程序被销毁
try {
Connection c=(Connection) arg0.getServletContext().getAttribute("connection");
c.close();
} catch (SQLException e) { e.printStackTrace();
} } @Override
public void contextInitialized(ServletContextEvent arg0) {
//应用程序被加载及初始化
try {
//连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/books","root","root");
arg0.getServletContext().setAttribute("connection", con);
} catch (Exception e) {
e.printStackTrace();
} } }

2)ServletContextAttributeListener接口方法:

 package com.cy.listener;

 import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener; public class MyServletContext implements ServletContextAttributeListener { @Override
public void attributeAdded(ServletContextAttributeEvent event) {
System.out.println("添加一个ServletContext属性"+event.getName()+"========="+event.getValue());//回传属性的名称 值
} @Override
public void attributeRemoved(ServletContextAttributeEvent event) {
System.out.println("删除一个ServletContext属性"+event.getName()+"========="+event.getValue());
} @Override
public void attributeReplaced(ServletContextAttributeEvent event) {
System.out.println("某个ServletContext属性被改变"+event.getName()+"========="+event.getValue());
} }
 package com.cy.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 Test extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
getServletContext().setAttribute("username", "tiger");
getServletContext().setAttribute("username", "kitty");
getServletContext().removeAttribute("username");
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} }

结果:

添加一个ServletContext属性username=========tiger
某个ServletContext属性被改变username=========tiger
删除一个ServletContext属性username=========kitty

四:监听会话范围内事件

1)HttpSessionBindingListener接口
注意:HttpSessionBindingListener接口是唯一不需要在web.xml设定的listener;
当我们的类实现了HttpSessionBindingListener接口后,只要这个对象加入Session范围(即调用HttpSession对象的setAttribute方法的时候)或从Session对象移出(即调用HttpSession对象的removeAttribute方法的时候或Session超时时)容器就会通知这个对象,分别会自动调用下列两个方法:
–void valueBound(HttpSessionBindingEvent event):当对象正在绑定到Session中,Servlet容器调用该方法来通知该对象
–void valueUnbound(HttpSessionBindingEvent event):当从Session中删除对象时,Servlet容器调用该方法来通知该对象

HttpSessionBindingEvent类提供如下方法:

public String getName():返回绑定到Session中或从Session中删除的属性名字。

public Object getValue():返回被添加、删除、替换的属性值

public HttpSession getSession():返回HttpSession对象

 
2)HttpSessionAttributeListener接口
监听HttpSession中的属性的操作
–当在Session中增加一个属性时,激发attributeAdded(HttpSessionBindingEvent event) 方法;
–当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent event)方法;
–当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent event) 方法。 
 
 3)HttpSessionListener接口
监听HttpSession对象的创建和销毁操作
-当创建一个Session时,激发session Created(HttpSessionEvent event)方法
–当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent event)方法
例子:可用于在线人数的统计
主要代码:
 package com.cy;

 public class OnlineCounter {
private static int online=0; public static int getOnlie(){
return online;
}
public static void raise(){
online++;
}
public static void reduce(){
online--;
} } package com.cy; import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; public class OnlineConter implements HttpSessionListener{ @Override
public void sessionCreated(HttpSessionEvent arg0) {
OnlineCounter.raise();
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
OnlineCounter.reduce();
} } package com.cy; 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 TestServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
HttpSession sess=req.getSession();
sess.setMaxInactiveInterval(10);
resp.getWriter().print("当前在线人数为:"+OnlineCounter.getOnlie());
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} }

五:监听请求生命周期内事件

请求作用域范围内的生命周期事件用于管理整个request生命周期的状态和资源
ServletRequestListener接口
–public void requestDestroyed(ServletRequestEvent event):当请求被销毁时被处理。
–public void requestInitialized(ServletRequestEvent event):当请求被创建时被处理
ServletRequestAttributeListener接口
–public void attributeAdded(ServletRequestAttributeEvent event) :当在请求作用域中添加一个属性的时候调用该方法。
–public void attributeRemoved(ServletRequestAttributeEvent event) :当在请求作用域中删除一个属性时调用
–public void attributeReplaced(ServletRequestAttributeEvent event) :当在请求作用域中替换一个属性值的时候调用
 
总结:
1 在Servlet中3个对象作用域分别由ServletContext、ServletRequest和HttpSession接口来处理
2 上下文作用域中设置的属性是线程不安全的
3 对于同一个客户的多个请求,Session会跨这些请求持久存储
4 设置在上下文和会话作用域中的对象,会非常消耗系统的资源
5 请求作用域范围仅仅作用在与一个请求相关的两个资源之间
6 应用程序事件监听器是实现一到多个Servlet事件监听器接口的类。它们在Web应用程序部署的时候,被Web容器初始化和注册
7 ServletContext监听器用于管理应用程序JVM级别保存的资源或状态。
8 HTTP会话监听器用于管理从同一客户端或用户发送的一系列请求的资源或状态。
9 Request请求监听器用于管理Request请求生命周期内的状态  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

第六章 对象作用域与servlet事件监听器的更多相关文章

  1. Servlet事件监听器

    监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行. 面试题:请描述一下java事件监听机 ...

  2. 【笔记】javascript权威指南-第六章-对象

    对象 //本书是指:javascript权威指南    //以下内容摘记时间为:2013.7.28 对象的定义: 1.对象是一种复合值:将很多值(原始值或者对象)聚合在一起,可以通过名字访问这些值. ...

  3. 《JS权威指南学习总结--第六章 对象》

    内容要点: 一.对象定义 对象是JS的基本数据类型.对象是一种复合值:它将很多值(原始值或者其他对象)聚合在一起,可通过名字访问这些值. 对象也可看做是属性的无序集合,每个属性都是一个名/值对. 属性 ...

  4. 快学Scala-第六章 对象

    知识点: 1.单例对象 使用object语法结构达到静态方法和静态字段的目的,如下例,对象定义某个类的单个实例,包含想要的特性,对象的构造器在该对象第一次被使用时调用. object Account{ ...

  5. 第六章 对象-javaScript权威指南第六版(四)

    6.6 属性getter和setter 对象属性是由名字.值和一组特性(attribute)构成的. getter和setter定义的属性称做"存取器属性"(accessor pr ...

  6. 第六章 对象-javaScript权威指南第六版(三)

    6.3 删除内容 delete运算符可以删除对象的属性. delete运算符只能删除自有属性,不能删除继承属性. delete表达式删除成功或没有任何副作用时,它返回true. 6.4 检测属性 用i ...

  7. 第六章 对象-javaScript权威指南第六版(二)

    通过原型 继承创建一个新对象,对于这一个函数的有说不出的感觉,看看语句都很简单,深层次的东西就是不知道 function inherit(p) { if(p == null)  throw TypeE ...

  8. 第六章 对象-javaScript权威指南第六版

    什么是对象? 对象是一种复合值,每一个属性都是都是一个名/值对.原型式继承是javaScript的核心特征. 对象常见的用法有,create\set\query\delete\test\enumera ...

  9. javascript面向对象精要第六章对象模式整理精要

    混入是一种给对象添加功能同时避免继承的强有力的方式,混入时将一个属性从一个对象 复制到另一个,从而使得接收者在不需要继承的情况下获得其功能.和继承不同,混入之后 对象无法检查属性来源.因此混入最适宜用 ...

随机推荐

  1. bootstrap4.2 导航搜索框

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  2. Anroid 手机助手 详细解析 概述(二)

    这篇主要说一下手机插入之后的一些动作. 1)  捕获窗口消息 插入拔出一个USB设备windows 会给所有的窗口发送特定的消息,只要我们捕获这些消息就可以处理设备插入和拔出.需要注意的是插入或者拔出 ...

  3. AngularJS 指令生命周期 complie link

    AnguarJS指令从解析到生效一共会经历Inject.Compile.Controller加载.Pre-link.Post-link这几个主要阶段. 一.AngularJS指令执行过程 1.加载An ...

  4. RxSwift学习笔记1:RxSwift的编程风格

    第一天:简单体验与RxSwift的编程风格 import UIKit//导入Rx相关框架 import RxSwift import RxCocoa struct Music { let name:S ...

  5. nfs 客户端挂住

    mount -t nfs -o soft,retry=1,timeo=10,intr 192.168.9.27:/mnt/vm /mnt/nfs-vm 可以让NFS client在连接不到NFS se ...

  6. Change tab position of PageControl to bottom

    Hi, Try: UniPageControl1 -> ClientEvents -> UniEvents : function tabPanel.beforeInit(sender, c ...

  7. 【vue】项目编译报错‘npm ERR! **@**dev: `webpack-dev-server --inline --progress --config ’’

    关于npm ERR! **@**dev: `webpack-dev-server --inline --progress --config‘ 原因:这是新版webpack存在的BUG,卸载现有的新版本 ...

  8. [CTSC2008]网络管理(整体二分+树剖+树状数组)

    一道经典的带修改树链第 \(k\) 大的问题. 我只想出三个 \(\log\) 的解法... 整体二分+树剖+树状数组. 那不是暴力随便踩的吗??? 不过跑得挺快的. \(Code\ Below:\) ...

  9. Spring 扫描标签<context:component-scan/>

    一. <context:annotation-config/> 此标签支持一些注入属性的注解, 列如:@Autowired, @Resource注解 二. <context:comp ...

  10. 社会地位即服务, Status as a Service (二): 社交网络的投资回报率 (ROI)

    本文作者 Eugene Wei 是 Amazon 战略部门的第一位分析师,后来还担任过 Flipboard, Hulu, Oculus 的产品负责人. 原文标题是 Status as a Servic ...