zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【web后端(十四)】jsp、servlet_监听器

JSPWeb后端Servlet 十四 监听器
2023-09-11 14:20:37 时间

监听器有几种类型,分别在一些服务器组件创建和销毁等时间节点要调用的接口,最常用的是ServletContextListener 。

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
   
    <!--这里没有名字的原因是因为,只要服务器请求的点上。他就会自动执行,不需要服务器去请求它。-->
    <listener>
        <listener-class>edu.xalead.listenter.ContextListener</listener-class>
    </listener>
   
</web-app>

ContextListener

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;

//服务器开始的时候,
// 执行ServletContextListener的contextInitialized初始化方法。
//销毁的时候,执行contextDestroyed方法。
//对于ServletContextListener,服务器开启的时候初始化,关闭的时候销毁。
//我们可以将调度程序写到里头。
//实际上,不只是ServletContext有监听器,
//request、session等也有。
public class ContextListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public ContextListener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("服务器启动。。。。。。");
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
    }

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
    }
}