ServletContextListener Servlet侦听器示例

本文是Java Web Application系列的第五部分,介绍了Servlet侦听器的概念,包括ServletContextListener、ServletContextAttributeListener、HttpSessionListener和ServletRequestListener。这些监听器用于在特定事件发生时执行任务,如会话创建、销毁等。文章详细讲解了每个监听器接口及其在Web应用程序中的作用,并提供了配置和使用示例。
摘要由CSDN通过智能技术生成

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 Application

    Java Web应用程序
  2. Servlets in Java

    Java中的Servlet
  3. Servlet Session Management

    Servlet会话管理
  4. Servlet Filter

    Servlet过滤器

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 Objects

    Servlet侦听器接口和事件对象
  3. Servlet Listener Configuration

    Servlet侦听器配置
  4. Servlet Listener Example

    Servlet侦听器示例
  5. ServletContextListener

    ServletContextListener
  6. ServletContextAttributeListener

    ServletContextAttributeListener
  7. HttpSessionListener

    HttpSessionListener
  8. ServletRequestListener

    ServletRequestListener
  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 context
        	DBConnectionManager 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%0
    
    
    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=88A7A1388AB96F611840886012A4475F
    Session Destroyed:: ID=88A7A1388AB96F611840886012A4475F
    ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0
    
    
    Database 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.

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值