4.监听器Listener

一、监听器Listener

javaEE包括13门规范 我们主要研究 servlet技术 和 jsp技术 其中 servlet规范包括三个技术点:servlet  listener  filter

1.什么是监听器?

监听器就是监听某个对象状态变化的组件

监听器的相关概念:

   事件源:被监听的对象  ----- 三个域对象 request  session  servletContext

   监听器:监听事件源对象  事件源对象的状态变化都会触发监听器 ---- 6+2种

   注册监听器:将监听器与事件源进行绑定

   响应行为:监听器监听到事件源的状态变化时 所涉及的功能代码 ---- 程序员编写代码

2.监听器有哪些?

第一维度:按照被监听的对象划分:  ServletRequest域   HttpSession域      ServletContext域

第二维度:监听的内容分:监听域对象的创建与销毁的    监听域对象的属性变化的

3.监听三大域对象的创建与销毁的监听器

   (1) 监听ServletContext域的创建与销毁的监听器ServletContextListener

    1)Servlet域的生命周期

          何时创建:服务器启动创建

          何时销毁:服务器关闭销毁

    2)监听器的编写步骤(重点):

  1. 编写一个监听器类去实现监听器接口
  2. 覆盖监听器的方法
  3. 需要在web.xml中进行配置---注册

    3) ServletContextListener监听器的主要作用

  1. 初始化的工作:初始化对象 初始化数据 ---- 加载数据库驱动  连接池的初始化
  2. 加载一些初始化的配置文件 --- spring的配置文件
  3. 任务调度----定时器----Timer/TimerTask
package com.xiaowei.create;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

//1.实现ServletContextListener接口
public class MyServletContextListener implements ServletContextListener {

	// 2.重写ServletContextListener接口的方法
	// 监听context域对象的创建
	public void contextInitialized(ServletContextEvent sce) {
		// 被监听的对象 ServletContext
		ServletContext servletContext = sce.getServletContext();
		// 被监听的对象 ServletContext 这是一种通用的方法
		Object source = sce.getSource();
		System.out.println("servlet对象创建了");

		// ServletContext的作用 开启一个定时器
		// 开启一个计息任务调度----每天晚上12点 计息一次
		Timer time = new Timer();
		// task:任务 firstTime:第一次执行时间 period:间隔执行时间
		// timer.scheduleAtFixedRate(task, firstTime, period);
		time.schedule(new TimerTask() {
			public void run() {
				System.out.println("傻特傻了 傻了 傻了");
			}
		}, new Date(), 4000);

		// 修改成银行真实计息业务
		// 1、起始时间: 定义成晚上12点
		// 2、间隔时间:24小时
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String currentTime = "2018-11-28 17:21:00";
		Date data = null;
		try {
			// 将时间的字符串转换成Date类型
			data = format.parse(currentTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// 执行定时操作
		time.schedule(new TimerTask() {
			public void run() {
				System.out.println("傻特来了");
			}
		}, data, 1000 * 60 * 60 * 24);

	}

	// 监听context域对象的销毁
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("servlet对象销毁了");
	}

	// 3.在web.xml文件中进行配置--注册
}
web.xml文件
	<listener>
		<listener-class>com.xiaowei.create.MyServletContextListener</listener-class>
	</listener>

(2)监听Httpsession域的创建于销毁的监听器HttpSessionListener

         1)HttpSession对象的生命周期

              何时创建:第一次调用request.getSession时创建

              何时销毁:服务器关闭销毁  session过期  手动销毁

         创建一个jsp文件 然后在浏览器中访问这个jsp文件就可以演示httpSessionListener了 因为jsp文件中默认的session=true

package com.xiaowei.create;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


//1.实现接口HttpSessionListener
public class MyHttpSessionLister implements HttpSessionListener{
//	2.重写方法
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("session创建");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("session销毁");
	}

}

 

3.在web.xml文件中注册
    <listener>
		<listener-class>com.xiaowei.create.MyHttpSessionLister</listener-class>
	</listener>

(3)监听ServletRequest域创建与销毁的监听器ServletRequestListener

  1. ServletRequest的生命周期

     创建:每一次请求都会创建request

     销毁:请求结束

4.监听三大域对象的属性变化的

  1. 域对象的通用的方法:

         setAttribute(name,value)

                  --- 触发添加属性的监听器的方法  

                  --- 触发修改属性的监听器的方法

         getAttribute(name)

         removeAttribute(name)  --- 触发删除属性的监听器的方法

package com.xiaowei.attribute;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

//1.实现ServletContextAttributeListener接口
public class MyServletContextAttributeListener implements ServletContextAttributeListener{

//	2.重写接口的方法
//	添加到域中的属性
	public void attributeAdded(ServletContextAttributeEvent scab) {
		System.out.println("add"+ scab.getName());  //放到域中的name
		System.out.println("add"+scab.getValue()); //放到域中的value
	}

//	删除域中的属性
	public void attributeRemoved(ServletContextAttributeEvent scab) {
		System.out.println("remove"+scab.getName());  //删除域中的name
		System.out.println("remove"+scab.getValue()); //删除域中的value
	}

	//重置域中的属性
	public void attributeReplaced(ServletContextAttributeEvent scab) {
		
		System.out.println("replace"+scab.getName());  //获得修改前域中的name
		System.out.println("replace"+scab.getValue()); //获得修改前域中的value
	}
	
//	3.在web.xml文件中注册		
}
  在web.xml文件中注册
  <listener>
  		<listener-class>com.xiaowei.attribute.MyServletContextAttributeListener</listener-class>
  </listener>
package com.xiaowei.attribute;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestMyServletContextAttributeListener extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		1.获取servletContext
		ServletContext servletContext = this.getServletContext();
		servletContext.setAttribute("name", "shate");
		servletContext.setAttribute("name", "feifei");
		servletContext.removeAttribute("name");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

5.与session中的绑定的对象相关的监听器(对象感知监听器)

  1. 即将要被绑定到session中的对象有几种状态

      绑定状态:就是一个对象被放到session域中

      解绑状态:就是这个对象从session域中移除了

      钝化状态:是将session内存中的对象持久化(序列化)到磁盘

      活化状态:就是将磁盘上的对象再次恢复到session内存中

      面试题:当用户很多时,怎样对服务器进行优化?

     2.绑定与解绑的监听器HttpSessionBindingListener

package com.xiaowei.domain;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

//1.实现HttpSessionBindingListener 它针对的是httpsession域中的对象
public class Person implements HttpSessionBindingListener{
	
//	3.属性
	private String id;
	private String name;
	private String age;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	//	2.重写方法  这个不用注册
//	绑定方法
	public void valueBound(HttpSessionBindingEvent event) {
		System.out.println("person被绑定了");
	}
//	解绑方法
	public void valueUnbound(HttpSessionBindingEvent event) {
		System.out.println("person被解绑了");
	}

}
package com.xiaowei.domain;

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 TestPersonBindingServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//		1.获取httpSession
		HttpSession session = request.getSession();
		Person p = new Person();
		p.setId("1");
		p.setName("shate");
		p.setAge("26");
		
		session.setAttribute("person", p);
		session.removeAttribute("person");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

3.钝化与活化的监听器HttpSessionActivationListener

可以通过配置文件 指定对象钝化时间 --- 对象多长时间不用被钝化

在META-INF下创建一个context.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<Context>
 <!-- maxIdleSwap:session中的对象多长时间不使用就钝化  单位是分钟-->
 <!-- directory:钝化后的对象的文件写到磁盘的哪个目录下  配置钝化的对象文件在work/catalina/localhost/钝化文件 -->
 <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
  <Store className="org.apache.catalina.session.FileStore" directory="shate23" />
 </Manager>
</Context>
package com.xiaowei.domain;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;

//1.实现HttpSessionActivationListener接口  
//注意 将对象存放到磁盘中一定要实现Serializable接口
public class Customer implements HttpSessionActivationListener,Serializable{

	private String id;
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
//	2.重写这个接口中的方法
//	钝化的方法
	public void sessionWillPassivate(HttpSessionEvent se) {
		System.out.println("customer被钝化了");
	}
//	活化的方法
	public void sessionDidActivate(HttpSessionEvent se) {
		System.out.println("customer被活化了");	
	}
		
}
package com.xiaowei.domain;

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 TestCustomerActiveServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		1.获取session
		HttpSession session = request.getSession();
		
		Customer customer = new Customer();
		customer.setId("1");
		customer.setName("shate");
		session.setAttribute("customer", customer);
		
		System.out.println("customer存里面了");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
package com.xiaowei.domain;

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 TestCustomerActiveServlet1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		1.获取session
		HttpSession session = request.getSession();
		Customer customer = (Customer) session.getAttribute("customer");
		System.out.println(customer.getName());
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/qq_43629005/article/details/84590086