六、Servlet监听器的分类

本文介绍了Servlet监听器的三种主要类型:1) 监听域对象创建和销毁,包括ServletContextListener、HttpSessionListener和ServletRequestListener;2) 监听域对象属性的增加和删除,涉及ServletContextAttributeListener、HttpSessionAttributeListener和ServletRequestAttributeListener;3) 监听HttpSession中对象状态的HttpBindingListener和HttpSessionActivationListener。通过实例展示了如何配置和使用这些监听器。
摘要由CSDN通过智能技术生成

二、监听的分类(按监听的事件划分)

1、监听域对象自身的创建和销毁的事件监听器

如下:

这里写图片描述

1.1、ServletContext——>ServletContextListener接口介绍如下:

ServletContextListener接口,主要实现监听ServletContext的创建和删除。同时它提供了两个方法,它们被称为“Web应用程序的生命周期方法”。

  • public void contextDestroyed(ServletContextEvent sce) {………………….}:通知正在收听的对象,应用程序已经被加载及初始化
  • public void contextInitialized(ServletContextEvent sce) {……………………}:通知正在收听的对象,应用程序已经被关闭。

这里写图片描述

例子:测试ServletContextListener

这里写图片描述

创建FistListener.java

package com;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class FirstListener implements ServletContextListener {
   

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("destroy");  
    }
    public void contextInitialized(ServletContextEvent sce) {
    //通过上下文getServletContext(),和getInitParameter()获取web.xml值
String init=sce.getServletContext().getInitParameter("init");
        System.out.println("init的值为:"+init);
    }
}

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>FirstListener</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>com.FirstListener<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值