@WebListener 注解方式实现监听

1.创建 Dynamic Web Project ,Dynamic Web module version选择3.0

 

2.在自动生成 的web.xml配置,增加 metadata-complete="false"

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <javaee:web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3 xmlns="http://Java.sun.com/xml/ns/javaee"
 4 xmlns:javaee="http://java.sun.com/xml/ns/javaee" 
 5 xmlns:web="http://java.sun.com/xml/ns/javaee" 
 6 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 7  metadata-complete="false" version="3.0">
 8   <javaee:display-name></javaee:display-name>
 9   <javaee:welcome-file-list>
10     <javaee:welcome-file>index.html</javaee:welcome-file>
11   </javaee:welcome-file-list>
12 </javaee:web-app>
复制代码

 

 

3.创建监听类,在监听类头部增加 注解 @WebListener

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.xhkj.listener;import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletContextListener implements ServletContextListener {
     @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("===========================MyServletContextListener销毁");
        }
 
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.println("===========================MyServletContextListener初始化");
            System.out.println(sce.getServletContext().getServerInfo());
        }
 
}

 

4.启动tomcat服务。打印结果如下

 

5 注意事项,每次修改配置或者java代码后,要重新编译,否则不起作用

 

6 代码所在地址

https://files.cnblogs.com/files/xhkj/TestWebListener.rar

 

  

posted @   拜占廷船长  阅读(14765)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示