1. 程式人生 > >@WebListener 註解方式實現監聽

@WebListener 註解方式實現監聽

sun listener etc 修改 tom imp exti .get xsd

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

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代碼後,要重新編譯,否則不起作用

  

@WebListener 註解方式實現監聽