ServletContextListener is one of the many Servlet Listener we have. This is the fifth article in the series of Java Web Application, you might want to check out earlier four articles too.

ServletContextListener是我们拥有的许多Servlet侦听器之一。 这是Java Web Application系列的第五篇文章,您可能还想看看前面的四篇文章。

  1. Java Web ApplicationJava Web应用程序
  2. Servlets in JavaJava中的Servlet
  3. Servlet Session ManagementServlet会话管理
  4. Servlet FilterServlet过滤器

Servlet侦听器 (Servlet Listener)

In this tutorial, we will look into servlet listener, benefits of servlet listeners, some common tasks that we can do with listeners, servlet API listener interfaces and Event objects. In the end we will create a simple web project to show example of commonly used Listener implementation for ServletContext, Session and ServletRequest.

在本教程中,我们将研究Servlet侦听器Servlet侦听器的优点,可以使用侦听器执行的一些常见任务,Servlet API侦听器接口和Event对象。 最后,我们将创建一个简单的Web项目,以显示ServletContextSessionServletRequest的常用侦听器实现的示例。

  1. Why do we have Servlet Listener?为什么我们有Servlet Listener?
  2. Servlet Listener Interfaces and Event ObjectsServlet侦听器接口和事件对象
  3. Servlet Listener ConfigurationServlet侦听器配置
  4. Servlet Listener ExampleServlet侦听器示例
  5. ServletContextListenerServletContextListener
  6. ServletContextAttributeListenerServletContextAttributeListener
  7. HttpSessionListenerHttpSessionListener
  8. ServletRequestListenerServletRequestListener
  1. 为什么我们有Servlet Listener? (Why do we have Servlet Listener?)

  2. We know that using ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in deployment descriptor (web.xml). What if our application is database oriented and we want to set an attribute in ServletContext for Database Connection. If you application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if database is down or not configured properly, we won’t know until first client request comes to server. To handle these scenario, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.

    我们知道,使用ServletContext可以创建具有所有其他Servlet都可以访问的应用程序范围的属性,但是我们只能在部署描述符(web.xml)中将ServletContext初始化参数初始化为String 。 如果我们的应用程序是面向数据库的,并且我们想在ServletContext中为数据库连接设置一个属性,该怎么办? 如果您的应用程序只有一个入口点(用户登录),那么您可以在第一个servlet请求中进行操作,但是如果我们有多个入口点,那么在任何地方都进行操作将导致大量代码冗余。 另外,如果数据库关闭或配置不正确,我们将直到第一个客户端请求到达服务器时才知道。 为了处理这些情况,Servlet API提供了侦听器接口,我们可以将其实现和配置为侦听事件并执行某些操作。

    Event is occurrence of something, in web application world an event can be initialization of application, destroying an application, request from client, creating/destroying a session, attribute modification in session etc.

    事件是某事的发生,在Web应用程序世界中,事件可以是应用程序初始化,破坏应用程序,来自客户端的请求,创建/销毁会话,在会话中进行属性修改等。

    Servlet API provides different types of Listener interfaces that we can implement and configure in web.xml to process something when a particular event occurs. For example, in above scenario we can create a Listener for the application startup event to read context init parameters and create a database connection and set it to context attribute for use by other resources.

    Servlet API提供了不同类型的侦听器接口,我们可以在web.xml中实现和配置这些侦听器接口,以在发生特定事件时处理某些内容。 例如,在上述情况下,我们可以为应用程序启动事件创建一个侦听器,以读取上下文初始化参数并创建数据库连接,并将其设置为上下文属性以供其他资源使用。

  3. Servlet侦听器接口和事件对象 (Servlet Listener Interfaces and Event Objects)

  4. Servlet API provides different kind of listeners for different types of Events. Listener interfaces declare methods to work with a group of similar events, for example we have ServletContext Listener to listen to startup and shutdown event of context. Every method in listener interface takes Event object as input. Event object works as a wrapper to provide specific object to the listeners.

    Servlet API为不同类型的事件提供了不同种类的侦听器。 侦听器接口声明用于与一组类似事件一起工作的方法,例如,我们有ServletContext侦听器来侦听上下文的启动和关闭事件。 侦听器接口中的每个方法都将Event对象作为输入。 事件对象充当包装器,以向侦听器提供特定的对象。

    Servlet API provides following event objects.

    Servlet API提供以下事件对象。

    1. javax.servlet.AsyncEvent – Event that gets fired when the asynchronous operation initiated on a ServletRequest (via a call to ServletRequest#startAsync or ServletRequest#startAsync(ServletRequest, ServletResponse)) has completed, timed out, or produced an error.javax.servlet.AsyncEvent-对ServletRequest发起的异步操作(通过调用ServletRequest#startAsync或ServletRequest#startAsync(ServletRequest,ServletResponse))完成,超时或产生错误时将触发的事件。
    2. javax.servlet.http.HttpSessionBindingEvent – Events of this type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the web.xml when any attribute is bound, unbound or replaced in a session.
      The session binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute.
      We can use this event for cleanup activities when object is removed from session.javax.servlet.http.HttpSessionBindingEvent –这种类型的事件或者在绑定或从会话取消绑定时发送到实现HttpSessionBindingListener的对象,或者在绑定任何属性时发送到在web.xml中配置的HttpSessionAttributeListener,在会话中未绑定或替换。
      会话通过调用HttpSession.setAttribute来绑定对象,并通过调用HttpSession.removeAttribute来取消绑定对象。
      当从会话中删除对象时,我们可以将此事件用于清理活动。
    3. javax.servlet.http.HttpSessionEvent – This is the class representing event notifications for changes to sessions within a web application.javax.servlet.http.HttpSessionEvent-这是一个类,表示Web应用程序中会话更改的事件通知。
    4. javax.servlet.ServletContextAttributeEvent – Event class for notifications about changes to the attributes of the ServletContext of a web application.javax.servlet.ServletContextAttributeEvent –事件类,用于通知有关Web应用程序ServletContext属性更改的通知。
    5. javax.servlet.ServletContextEvent – This is the event class for notifications about changes to the servlet context of a web application.javax.servlet.ServletContextEvent-这是事件类,用于通知有关Web应用程序Servlet上下文更改的信息。
    6. javax.servlet.ServletRequestEvent – Events of this kind indicate lifecycle events for a ServletRequest. The source of the event is the ServletContext of this web application.javax.servlet.ServletRequestEvent –这种事件表示ServletRequest的生命周期事件。 事件的来源是此Web应用程序的ServletContext。
    7. javax.servlet.ServletRequestAttributeEvent – This is the event class for notifications of changes to the attributes of the servlet request in an application.javax.servlet.ServletRequestAttributeEvent-这是事件类,用于通知应用程序中Servlet请求的属性更改。

    Servlet API provides following Listener interfaces.

    Servlet API提供以下侦听器接口。

    1. javax.servlet.AsyncListener – Listener that will be notified in the event that an asynchronous operation initiated on a ServletRequest to which the listener had been added has completed, timed out, or resulted in an error.javax.servlet.AsyncListener-如果在添加了侦听器的ServletRequest上发起的异步操作已完成,超时或导致错误,则将通知该侦听器。
    2. javax.servlet.ServletContextListener – Interface for receiving notification events about ServletContext lifecycle changes.javax.servlet.ServletContextListener-接收有关ServletContext生命周期更改的通知事件的接口。
    3. javax.servlet.ServletContextAttributeListener – Interface for receiving notification events about ServletContext attribute changes.javax.servlet.ServletContextAttributeListener-接收有关ServletContext属性更改的通知事件的接口。
    4. javax.servlet.ServletRequestListener – Interface for receiving notification events about requests coming into and going out of scope of a web application.javax.servlet.ServletRequestListener-用于接收有关进入和离开Web应用程序范围的请求的通知事件的接口。
    5. javax.servlet.ServletRequestAttributeListener – Interface for receiving notification events about ServletRequest attribute changes.javax.servlet.ServletRequestAttributeListener-接收有关ServletRequest属性更改的通知事件的接口。
    6. javax.servlet.http.HttpSessionListener – Interface for receiving notification events about HttpSession lifecycle changes.javax.servlet.http.HttpSessionListener-接收有关HttpSession生命周期更改的通知事件的接口。
    7. javax.servlet.http.HttpSessionBindingListener – Causes an object to be notified when it is bound to or unbound from a session.javax.servlet.http.HttpSessionBindingListener –使对象绑定到会话或从会话取消绑定时得到通知。
    8. javax.servlet.http.HttpSessionAttributeListener – Interface for receiving notification events about HttpSession attribute changes.javax.servlet.http.HttpSessionAttributeListener-接收有关HttpSession属性更改的通知事件的接口。
    9. javax.servlet.http.HttpSessionActivationListener – Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.javax.servlet.http.HttpSessionActivationListener-绑定到会话的对象可以侦听容器事件,通知它们将钝化会话并激活该会话。 需要一个在VM之间迁移会话或保留会话的容器,以通知绑定到实现HttpSessionActivationListener的会话的所有属性。
  5. Servlet侦听器配置 (Servlet Listener Configuration)

  6. We can use @WebListener annotation to declare a class as Listener, however the class should implement one or more of the Listener interfaces.

    我们可以使用@WebListener 批注将一个类声明为Listener,但是该类应实现一个或多个Listener接口。

    We can define listener in web.xml as:

    我们可以在web.xml中将侦听器定义为:

    <listener><listener-class>com.journaldev.listener.AppContextListener</listener-class>
    </listener>
  7. Servlet侦听器示例 (Servlet Listener Example)

  8. Let’s create a simple web application to see servlet listener in action. We will create dynamic web project in Eclipse ServletListenerExample those project structure will look like below image.

    让我们创建一个简单的Web应用程序以查看servlet侦听器的运行情况。 我们将在Eclipse ServletListenerExample中创建动态Web项目,这些项目结构如下图所示。

    web.xml: In deployment descriptor, I will define some context init params and listener configuration.

    web.xml :在部署描述符中,我将定义一些上下文初始化参数和侦听器配置。

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"><display-name>ServletListenerExample</display-name><context-param><param-name>DBUSER</param-name><param-value>pankaj</param-value></context-param><context-param><param-name>DBPWD</param-name><param-value>password</param-value></context-param><context-param><param-name>DBURL</param-name><param-value>jdbc:mysql://localhost/mysql_db</param-value></context-param><listener><listener-class>com.journaldev.listener.AppContextListener</listener-class></listener><listener><listener-class>com.journaldev.listener.AppContextAttributeListener</listener-class></listener><listener><listener-class>com.journaldev.listener.MySessionListener</listener-class></listener><listener><listener-class>com.journaldev.listener.MyServletRequestListener</listener-class></listener>
    </web-app>

    DBConnectionManager: This is the class for database connectivity, for simplicity I am not providing code for actual database connection. We will set this object as attribute to servlet context.

    DBConnectionManager :这是数据库连接的类,为简单起见,我不提供用于实际数据库连接的代码。 我们将这个对象设置为servlet上下文的属性。

    package com.journaldev.db;import java.sql.Connection;public class DBConnectionManager {private String dbURL;private String user;private String password;private Connection con;public DBConnectionManager(String url, String u, String p){this.dbURL=url;this.user=u;this.password=p;//create db connection now}public Connection getConnection(){return this.con;}public void closeConnection(){//close DB connection here}
    }

    MyServlet: A simple servlet class where I will work with session, attributes etc.

    MyServlet :一个简单的servlet类,我将在其中处理会话,属性等。

    package com.journaldev.servlet;import java.io.IOException;
    import java.io.PrintWriter;import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;@WebServlet("/MyServlet")
    public class MyServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletContext ctx = request.getServletContext();ctx.setAttribute("User", "Pankaj");String user = (String) ctx.getAttribute("User");ctx.removeAttribute("User");HttpSession session = request.getSession();session.invalidate();PrintWriter out = response.getWriter();out.write("Hi "+user);}}

    Now we will implement listener classes, I am providing sample listener classes for commonly used listeners – ServletContextListener, ServletContextAttributeListener, ServletRequestListener and HttpSessionListener.

    现在我们将实现侦听器类,我将为常用的侦听器提供样本侦听器类-ServletContextListener,ServletContextAttributeListener,ServletRequestListener和HttpSessionListener。

  9. ServletContextListener (ServletContextListener)

  10. We will read servlet context init parameters to create the DBConnectionManager object and set it as attribute to the ServletContext object.

    我们将读取servlet上下文初始化参数来创建DBConnectionManager对象,并将其设置为ServletContext对象的属性。

    package com.journaldev.listener;import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;import com.journaldev.db.DBConnectionManager;@WebListener
    public class AppContextListener implements ServletContextListener {public void contextInitialized(ServletContextEvent servletContextEvent) {ServletContext ctx = servletContextEvent.getServletContext();String url = ctx.getInitParameter("DBURL");String u = ctx.getInitParameter("DBUSER");String p = ctx.getInitParameter("DBPWD");//create database connection from init parameters and set it to contextDBConnectionManager dbManager = new DBConnectionManager(url, u, p);ctx.setAttribute("DBManager", dbManager);System.out.println("Database connection initialized for Application.");}public void contextDestroyed(ServletContextEvent servletContextEvent) {ServletContext ctx = servletContextEvent.getServletContext();DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager");dbManager.closeConnection();System.out.println("Database connection closed for Application.");}}
  11. ServletContextAttributeListener (ServletContextAttributeListener)

  12. A simple implementation to log the event when attribute is added, removed or replaced in servlet context.

    一个简单的实现,用于在Servlet上下文中添加,删除或替换属性时记录事件。

    package com.journaldev.listener;import javax.servlet.ServletContextAttributeEvent;
    import javax.servlet.ServletContextAttributeListener;
    import javax.servlet.annotation.WebListener;@WebListener
    public class AppContextAttributeListener implements ServletContextAttributeListener {public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {System.out.println("ServletContext attribute added::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");}public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {System.out.println("ServletContext attribute replaced::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");}public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {System.out.println("ServletContext attribute removed::{"+servletContextAttributeEvent.getName()+","+servletContextAttributeEvent.getValue()+"}");}}
  13. HttpSessionListener (HttpSessionListener)

  14. A simple implementation to log the event when session is created or destroyed.

    创建或销毁会话时记录事件的简单实现。

    package com.journaldev.listener;import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;@WebListener
    public class MySessionListener implements HttpSessionListener {public void sessionCreated(HttpSessionEvent sessionEvent) {System.out.println("Session Created:: ID="+sessionEvent.getSession().getId());}public void sessionDestroyed(HttpSessionEvent sessionEvent) {System.out.println("Session Destroyed:: ID="+sessionEvent.getSession().getId());}}
  15. ServletRequestListener (ServletRequestListener)

  16. A simple implementation of ServletRequestListener interface to log the ServletRequest IP address when request is initialized and destroyed.

    ServletRequestListener接口的一个简单实现,用于在初始化和销毁​​请求时记录ServletRequest IP地址。

    package com.journaldev.listener;import javax.servlet.ServletRequest;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    import javax.servlet.annotation.WebListener;@WebListener
    public class MyServletRequestListener implements ServletRequestListener {public void requestDestroyed(ServletRequestEvent servletRequestEvent) {ServletRequest servletRequest = servletRequestEvent.getServletRequest();System.out.println("ServletRequest destroyed. Remote IP="+servletRequest.getRemoteAddr());}public void requestInitialized(ServletRequestEvent servletRequestEvent) {ServletRequest servletRequest = servletRequestEvent.getServletRequest();System.out.println("ServletRequest initialized. Remote IP="+servletRequest.getRemoteAddr());}}

    Now when we will deploy our application and access MyServlet in browser with URL https://localhost:8080/ServletListenerExample/MyServlet, we will see following logs in the server log file.

    现在,当我们部署应用程序并使用URL https://localhost:8080/ServletListenerExample/MyServlet MyServlet在浏览器中访问MyServlet时,我们将在服务器日志文件中看到以下日志。

    ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@4def3d1b}
    Database connection initialized for Application.
    ServletContext attribute added::{org.apache.jasper.compiler.TldLocationsCache,org.apache.jasper.compiler.TldLocationsCache@1594df96}ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
    ServletContext attribute added::{User,Pankaj}
    ServletContext attribute removed::{User,Pankaj}
    Session Created:: ID=88A7A1388AB96F611840886012A4475F
    Session Destroyed:: ID=88A7A1388AB96F611840886012A4475F
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0Database connection closed for Application.

    Notice the sequence of logs and it’s in the order of execution. The last log will appear when you will shutdown the application or shutdown the container.

    注意日志的顺序,并按执行顺序。 当您关闭应用程序或关闭容器时,将显示最后一个日志。

Thats all for listener in servlet, we will look into cookies and some common servlet examples next.

这就是Servlet中侦听器的全部内容,接下来我们将研究cookie和一些常见的servlet示例。

You can download the project from below link and play around with it to learn more.

您可以从下面的链接下载该项目并进行试用以了解更多信息。

Download Servlet Listener Example Project下载Servlet侦听器示例项目

Check out next article in the series about Cookies in Servlet.

查阅有关Servlet中Cookies的系列的下一篇文章。

翻译自: https://www.journaldev.com/1945/servletcontextlistener-servlet-listener-example

ServletContextListener Servlet侦听器示例相关推荐

  1. Selenium WebDriver中的TestNG侦听器及示例

    Java提供了不同的接口,使您可以修改TestNG行为. 这些接口在Selenium WebDriver中进一步称为TestNG侦听器. TestNG Listeners还允许您根据项目要求自定义测试 ...

  2. testng 监听器_TestNG侦听器

    testng 监听器 TestNG Listeners are used to inspect and modify the testing behavior. TestNG listeners al ...

  3. Vue.js 计算属性和侦听器

    计算属性和侦听器 计算属性 模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的.在模板中放入太多的逻辑会让模板过重且难以维护.例如: <div id="example" ...

  4. 此计算机支持多个rdp侦听程序,远程桌面侦听器证书配置

    远程桌面侦听器证书配置 09/08/2020 本文内容 本文介绍在基于 Windows Server 2012 或基于 Windows Server 2012 的服务器上配置侦听器证书的方法,该服务器 ...

  5. 5.Vue 计算属性和侦听器

    Hello,我是 Alex 007,一个热爱计算机编程和硬件设计的小白,为啥是007呢?因为叫 Alex 的人太多了,再加上每天007的生活,Alex 007就诞生了. 5.Vue 计算属性和侦听器 ...

  6. vue 侦听器侦听对象属性_Spring中的异步和事务性事件侦听器

    vue 侦听器侦听对象属性 内置的事件发布功能从Spring的早期版本开始存在,并且对于处理同一应用程序上下文中Spring组件之间的基本通信仍然有用. 通常,应用程序可以生成应用程序事件(可以是任意 ...

  7. 侦听127.0.01_Spring 4.2中由注释驱动的事件侦听器

    侦听127.0.01 介绍 在应用程序内交换事件已成为许多应用程序中必不可少的部分,幸运的是,Spring为瞬态事件(*)提供了完整的基础结构. 最近对事务绑定事件的重构为我提供了一个借口,以在实践中 ...

  8. vue 侦听器侦听对象属性_不删除侦听器–使用ListenerHandles

    vue 侦听器侦听对象属性 听一个可观察的实例并对它的变化做出React很有趣. 做一些必要的事情来打断或结束这种聆听会变得很有趣. 让我们看看问题的根源和解决方法. 总览 这篇文章将首先讨论这种情况 ...

  9. 支付宝通知侦听器是什么_使用SWTEventHelper清除SWT侦听器通知

    支付宝通知侦听器是什么 为基于SWT的UI编写测试通常需要以编程方式通知小部件侦听器. 不幸的是,用于创建,初始化并最终触发事件的代码有点冗长,并且分散了测试的实际目的. 在编写了类似的初始化例程几次 ...

最新文章

  1. 2020 数据分析岗位报告:数据分析师需要哪些能力?
  2. oracle上机题库_Oracle数据库考试试题库
  3. iphone屏幕录制_无需第三方APP,苹果iPhone手机屏幕录制的方法
  4. python3.6 websocket异步高并发_Python3.6 websocket开发
  5. python 连续三个数满足条件_计算满足条件的连续值数(Pandas Dataframe)
  6. 双十一期间快递员凌晨送件 将下班程序员误认成小偷
  7. SpringBoot系列: 单元测试2
  8. 大屏监控系统实战(15)-打包上线及总结
  9. 3-3 修改haproxy配置文件
  10. 【树莓派】服务配置相关3:基于Ubuntu Server的服务配置
  11. Linux安装的分区问题
  12. VUe Eelement-ui 兼容es6 兼容IE9+ 报错:SCRIPT1003: 缺少 ':’
  13. CPU检测软件CPU-Z的下载使用
  14. linux下nginx和redis安装笔记
  15. AI学习路线和书籍分享
  16. python中3个单引号,Pyhton3中单引号、双引号、三个引号的用法和区别
  17. BZOJ 4199 品酒大会
  18. 连接中控指纹考勤机 zkemkeeper zksoftware ZKTeco
  19. 2022中山大学计算机考研专硕初试经验分享
  20. 三、jQuery 中的 DOM 操作(超详细)

热门文章

  1. Python 批量重命名文件
  2. Java学习笔记——JDBC读取properties属性文件
  3. Debian Squeeze 安装
  4. SPQuery如何消除重复记录(实现联动性)
  5. [转载] python的短逻辑
  6. [转载] 高阶函数和柯里化
  7. Winform 中 dataGridView 导出到Excel中的方法总结
  8. Which language is best, C, C++, Python or Java?什么编程语言最好
  9. 【字符串】面试题之替换子串
  10. Java nginx 双向ssl_nginx配置ssl双向验证 nginx https ssl证书配置