Java Web监听器Listener接口原理及用法实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java Web监听器Listener接口原理及用法实例

Esrevinud的笔记   2020-06-23 我要评论

本文着重讲解了Java Web监听器Listener接口原理及用法实例,文中通过代码实例讲解的非常细致,对大家的学习或者工作具有一定的参考学习价值,欢迎大家阅读和收藏

监听器主要针对三个对象

  • ServletContext
  • HttpSession
  • ServletRequest

使用方式

  • 创建*Listener接口的实现类
  • 在web.xml中注册该类

在同时注册多个同接口的监听器时,执行顺序参照web.xml中的注册顺序

  • 监听器监听类型
  • 对象的创建和销毁
  • 对象属性的添加、替换、移除

创建实现类

// 用于监听session创建和销毁的监听器
package listener;

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

public class SessionListener implements HttpSessionListener {
  @Override
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    // 获取本次事件创建session的id
    String sessionId = httpSessionEvent.getSession().getId();
    System.out.println("create session that id = " + sessionId);
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    // 删除session的id
    String sessionId = httpSessionEvent.getSession().getId();
    System.out.println("session has been destroy that id = " + sessionId);
  }
}

在web.xml中注册

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     id="WebApp_ID" version="3.1">
 <display-name>Archetype Created Web Application<https://img.qb5200.com/download-x/display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <listener>
 	<!-- 在listener包下的SessionListener类 -->
  <listener-class>listener.SessionListener</listener-class>
 </listener>

</web-app>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们