Javaweb---监听器

1.什么是监听器

监听器就是监听某个对象的状态变化的组件。
事件源:被监听的对象 ----- 三个域对象 request session servletContext
监听器:监听事件源对象 事件源对象的状态的变化都会触发监听器 ---- 6+2
注册监听器:将监听器与事件源进行绑定
响应行为:监听器监听到事件源的状态变化时 所涉及的功能代码 ---- 程序员编写代 码

ServletContext域HttpSession域ServletRequest域
域对象内的创建与销毁ServletContextListenerHttpSessionListenerServletRequestListener
域对象内的属性的变化ServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener
ServletContextListener监听器的主要作用
a、初始化的工作:初始化对象 初始化数据 ---- 加载数据库驱动  连接池的初始化
b、加载一些初始化的配置文件 --- spring的配置文件
c、任务调度----定时器----Timer/TimerTask

实现步骤:

1,编写一个监听器类去实现监听器接口

例如创建一个类,类名为:MyServletContextListener

2,覆盖监听器的方法(说白了去实现一下ServletContextListener这个接口,并且实现该接口未实现的方法就行)

public class ServletContextListener implements ServletContextListener{//监听context域对象的创建public void contextInitialized(ServletContextEvent sce) {System.out.println("context创建了...");}//监听context域对象的销毁public void contextDestroyed(ServletContextEvent sce) {System.out.println("context销毁了...");}}

3,需要在web.xml中进行配置—注册

把该方法的全包名给配置一下即可
<listener><listener-class>beyond.create.MyServletContextListener</listener-class>
</listener>

ServletContextListener
银行计息:

package beyond.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;public class MyServletContextListener implements ServletContextListener {//实现监听器接口ServletContext域的创建和销毁//监听context域对象的创建public void contextInitialized(ServletContextEvent sce) {//服务器启动的时候执行该方法System.out.println("context创建了...");//通过sce可以获得的被监听的对象//ServletContext servletContext = sce.getServletContext();//就是被监听的对象---ServletContext//ServletContext source = (ServletContext)sce.getSource();//getSource就是被监听的对象  是通用方法//开启一计息任务调度---每天晚上12点计息一次Timer timer = new Timer();//task:任务   firstTime:第一次执行时间  period:间隔执行时间//timer.schedule(task, firstTime, period);/*timer.schedule(new TimerTask() {//TimerTask为一个接口,可以通过匿名内部类进行newpublic void run() {System.out.println("银行计息了...");}}, new Date(), 5000);*///具体实现银行计息如下://修改成银行真实计息业务//1.起始时间:定义成晚上12点//2.间隔时间:24小时SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String currentTime = "2019-04-29 00:00:00";Date parse = null;try {parse = format.parse(currentTime);//解析字符串} catch (ParseException e) {e.printStackTrace();}timer.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("银行计息了...");}}, parse, 24*60*60*1000);//一天计息一次}//监听context域对象的销毁public void contextDestroyed(ServletContextEvent sce) {System.out.println("context销毁了...");}}

HttpSessionListener
创建与ServletContextListener一样,
继承接口,实现方法,web.xml进行配置
ServletRequestListener也一样

2,监听三大域对象的属性变化

1)域对象的通用方法:
setAttribute(name,value)
—触发添加属性的监听器的方法
—触发修改属性的监听器的方法
getAttribute(name)
removeAttribute(name) - - - 触发删除属性的监听器的方法

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

(1)即将要被绑定到session中的对象有几种状态
绑定状态:就一个对象被放到session域中
解绑状态:就是这个对象从session域中移除了
钝化状态:是将session内存中的对象持久化(序列化)到磁盘
活化状态:就是将磁盘上的对象再次恢复到session内存中

绑定与解绑

首先,HttpSessionBindingListener该监听器是绑定在对象上的,并且不需要配置web.xml,跟上面绑定监听器一样,继承接口,实现接口未实现的方法

package beyond.domain;import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;public class Person implements HttpSessionBindingListener{//该监听器是绑到对象身上的,不需要配置web.xmlprivate 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;}@Overridepublic void valueBound(HttpSessionBindingEvent event) {//绑定的方法System.out.println("Person被绑定了");}@Overridepublic void valueUnbound(HttpSessionBindingEvent event) {//解绑的方法System.out.println("Person被解绑了");}
}
package beyond.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 {HttpSession session = request.getSession();//先获得session//将person对象绑定到session中Person p = new Person();p.setId("100");p.setName("beyond");session.setAttribute("person", p);//将p对象(name为person)放到session域当中,被绑定//将person对象从session中解绑session.removeAttribute("person");//跟着name来的}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}

钝化与活化

钝化与活化的监听器HttpSessionActivationListener
钝化:是将session内存中的对象持久化(序列化)到磁盘
活化:就是将磁盘上的对象再次恢复到session内存中
当用户很多的时候,就需要用钝化和活化进行优化
与session有关的对象感知监听器一样,该监听器需要绑定在实体上,继承该监听器(HttpSessionActivationListener),这里特别注意要实现接口Serializable

public class Customer implements HttpSessionActivationListener,Serializable

例如:创建一个实体Customer,需要继承HttpSessionActivationListener这个监听器,并且实现该接口Serializable

package beyond.domain;import java.io.Serializable;import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;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;}@Override//服务器正常关闭时钝化public void sessionWillPassivate(HttpSessionEvent se) {//钝化---把session存到磁盘System.out.println("customer被钝化了");}@Override//服务器再次启动时活化public void sessionDidActivate(HttpSessionEvent se) {//活化---把磁盘恢复到session内存区域中System.out.println("customer被活化了");}}
钝化代码:
package beyond.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 {HttpSession session = request.getSession();//获得session对象Customer customer = new Customer();customer.setId("1014");customer.setName("wsq");session.setAttribute("customer", customer);//将customer放到session当中System.out.println("customer被放到session域中了");//钝化,已存到本地磁盘中去了}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
活化代码:
package beyond.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 TestCustomerActiveServlet2 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//从session域当中获得customerHttpSession session = request.getSession();//先获得sessionCustomer customer = (Customer) session.getAttribute("customer");//强转System.out.println(customer.getName());//活化后输出customer里面的customer对象的Name值}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
这里需要注意一下:可以通过配置文件 指定对象钝化时间—对象多长时间不适用被钝化

在这里插入图片描述
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"> <!-- 1分钟不用session被钝化到磁盘中 --><Store className="org.apache.catalina.session.FileStore" directory="itcast205" />  <!-- 将钝化后的session存放当itcast205该目录下,目录可以自定义 --></Manager>
</Context>
当再次运行Servlet的时候,钝化后的session会存到相关指定文件夹下

在这里插入图片描述

该文件夹下面的内容就是session里面的内容

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379531.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux中的Ramdisk和Initrd

Ramdisk简介先简单介绍一下ramdisk&#xff0c;Ramdisk是虚拟于RAM中的盘(Disk)。对于用户来说&#xff0c;能把RAM disk和通常的硬盘分区&#xff08;如/dev/hda1&#xff09;同等对待来使用&#xff0c;例如&#xff1a;redice # mkfs.ext2 /dev/ram0mke2fs 1.38 (30-Jun-200…

slab下kmalloc内核函数实现

文章目录kmalloc的整体实现获取高速缓存高速缓存获取index总结https://blog.csdn.net/qq_41683305/article/details/124554490&#xff0c;在这篇文章中&#xff0c;我们介绍了伙伴算法、slab机制和常见的内存管理函数&#xff0c;接下来&#xff0c;我们看看kmalloc内核函数的…

PHP array_merge_recursive()函数与示例

PHP array_merge_recursive()函数 (PHP array_merge_recursive() function) array_merge_recursive() function is used to merge two or more arrays, it returns a new array with merged elements. The only difference between array_merge() and array_merge_recursive() …

标题:三羊献瑞

标题&#xff1a;观察下面的加法算式&#xff1a; 其中&#xff0c;相同的汉字代表相同的数字&#xff0c;不同的汉字代表不同的数字。 请你填写“三羊献瑞”所代表的4位数字&#xff08;答案唯一&#xff09;&#xff0c;不要填写任何多余内容。 思路分析&#xff1a; 首先…

hdu 1069

地址&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1069 题意&#xff1a;给定若干个木块长宽高&#xff0c;长宽高可以自己调整&#xff0c;求堆积起来最高的高度。 mark&#xff1a;枚举所有木块长宽高可能情况&#xff0c;简单dp。 代码&#xff1a; #include <…

简明 Python 编程规范

简明 Python 编程规范编码 所有的 Python 脚本文件都应在文件头标上 # -*- coding:utf-8 -*- 。设置编辑器&#xff0c;默认保存为 utf-8 格式。注释 业界普遍认同 Python 的注释分为两种的概念&#xff0c;一种是由 # 开头的“真正的”注释&#xff0c;另一种是 docstri…

进程虚拟地址管理

文章目录1 地址分布实际使用中的内存区域2 进程的虚拟地址描述用户空间mmap线程之间共享内存地址的实现机制1 地址分布 现在采用虚拟内存的操作系统通常都使用平坦地址空间&#xff0c;平坦地址空间是指地址空间范围是一个独立的连续空间&#xff08;比如&#xff0c;地址从0扩…

java两个文件夹比较路径_比较Java中两个文件的路径

java两个文件夹比较路径Given the paths of the two files and we have two compare the paths of the files in Java. 给定两个文件的路径&#xff0c;我们有两个比较Java中文件的路径。 Comparing paths of two files 比较两个文件的路径 To compare the paths of two file…

标题:加法变乘法

标题&#xff1a;我们都知道&#xff1a;123 … 49 1225 现在要求你把其中两个不相邻的加号变成乘号&#xff0c;使得结果为2015 比如&#xff1a; 123…10*1112…27*2829…49 2015 就是符合要求的答案。 请你寻找另外一个可能的答案&#xff0c;并把位置靠前的那个乘号左…

C# winform对话框用法大全收藏

对话框中我们常用了以下几种&#xff1a; 1、文件对话框(FileDialog) 它又常用到两个&#xff1a; 打开文件对话框(OpenFileDialog) 保存文件对话(SaveFileDialog) 2、字体对话框(FontDialog) 3、颜色对话框(&#xff23;olorDialog) 4、打印预浏对话框(PrintPreviewDialog) 5、…

【翻译】eXpressAppFramework QuickStart 业务模型设计(四)—— 实现自定义业务类...

这一讲&#xff0c;你将学到如何从头开始实现业务类。为此&#xff0c;将要实现Department和Position业务类。这些类将被应用到之前实现的Contact类中。你将学到引用对象自动生成用户界面的基本要素。 在此之前&#xff0c;我建议你去阅读一下 【翻译】eXpressAppFramework Qui…

内存重映射

文章目录1 kmap2 映射内核内存到用户空间使用remap_pfn_range使用io_remap_pfn_rangemmap文件操作建立VMA和实际物理地址的映射mmap 之前分配 一次性映射mmap 之前分配 Page FaultPage Fault 中分配 映射内核内存有时需要重新映射&#xff0c;无论是从内核到用户空间还是从内…

math.sqrt 有问题_JavaScript中带有示例的Math.sqrt()方法

math.sqrt 有问题JavaScript | Math.sqrt()方法 (JavaScript | Math.sqrt() Method) The Math.sqrt() method is inbuilt in JavaScript to find the square root of a number. In this tutorial, we will learn about the sqrt() method with examples. JavaScript中内置了Mat…

标题:移动距离

标题&#xff1a;移动距离 X星球居民小区的楼房全是一样的&#xff0c;并且按矩阵样式排列。其楼房的编号为1,2,3… 当排满一行时&#xff0c;从下一行相邻的楼往反方向排号。 比如&#xff1a;当小区排号宽度为6时&#xff0c;开始情形如下&#xff1a; 1 2 3 4 5 6 12 11 1…

ISAPI Rewrite 实现简单url重写、二级域名重写

实现步骤&#xff1a; 第一步&#xff1a;下载ISAPI_Rewrite.rar&#xff0c;将Rewrite文件夹和httpd.ini直接放在项目根目录下面。 第二步&#xff1a;IIS配置&#xff0c;筛选Rewrite文件夹里面的Rewrite.dll文件&#xff0c;如图&#xff1a; 第三步&#xff1a;在httpd.ini…

用户登录

用户登录 代码namespace 用户登录 {public partial class Form1 : Form{public Form1(){InitializeComponent();}bool b1, b2, b3, b4, b5, b6;private void button1_Click(object sender, EventArgs e){try{if (b1 && b2 && b3 && b4 && b5 &…

进程上下文和中断上下文

文章目录进程的preempt_count变量thread_infopreempt_counthardirq相关softirq相关上下文原文链接&#xff1a; https://zhuanlan.zhihu.com/p/88883239进程的preempt_count变量 thread_info 在内核中&#xff0c;上下文的设置和判断接口可以参考 include/linux/preempt.h 文…

标题:凑算式

标题&#xff1a;凑算式 这个算式中AI代表19的数字&#xff0c;不同的字母代表不同的数字。 比如&#xff1a; 68/3952/714 就是一种解法&#xff0c; 53/1972/486 是另一种解法。 这个算式一共有多少种解法&#xff1f; 注意&#xff1a;你提交应该是个整数&#xff0c;不要…

汇编中imul_JavaScript中带有示例的Math.imul()方法

汇编中imulJavaScript | Math.imul()方法 (JavaScript | Math.imul() Method) Math.imul() is a function in math library of JavaScript that is used to the 32-bit multiplication of the two values passed to it. It uses C-like semantics to find the multiplication. …

AFTER触发器与INSTEAD OF触发器的区别

INSTEAD OF 触发器用来代替通常的触发动作&#xff0c;即当对表进行INSERT、UPDATE 或 DELETE 操作时&#xff0c;系统不是直接对表执行这些操作&#xff0c;而是把操作内容交给触发器&#xff0c;让触发器检查所进行的操作是否正确。如正确才进行相应的操作。因此&#xff0c;…