一、介绍
用于监听域对象Request、Session、ServletContext的初始化和销毁行为,当上述两个行为发生时,可以用定制的回调函数处理。
二、实现步骤
(1)实现对应域对象的监听器接口。
(2)重写初始化和销毁方法。
(3)在web.xml文件配置监听器。
三、项目演示
(1)创建MyServlet类并继承HttpServlet类,创建监听器MyListener类并实现ServletContextListener
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext...init");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("ServletContext...destroy");
}
}
(2)编写web.xml文件,配置Servlet和监听器
<?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">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.wsh.servlet.MyServlet</servlet-class>
<!--load-on-startup的值大于等于0时,Servlet在Tomcat启动时初始化-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/test01</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.wsh.listener.MyListener</listener-class>
</listener>
</web-app>
(3)配置Tomcat中的项目上下文路径
(4)运行