Servlet3.0學習總結(四)——使用注解標注監聽器(Listener)


  Servlet3.0提供@WebListener注解將一個實現了特定監聽器接口的類定義為監聽器這樣我們在web應用中使用監聽器時,也不再需要在web.xml文件中配置監聽器的相關描述信息了。

  下面我們來創建一個監聽器,體驗一下使用@WebListener注解標注監聽器,如下所示:

  

監聽器的代碼如下:

 1 package me.gacl.web.listener;
 2 
 3 import javax.servlet.ServletContextEvent;
 4 import javax.servlet.ServletContextListener;
 5 import javax.servlet.annotation.WebListener;
 6 
 7 /**
 8  * 使用@WebListener注解將實現了ServletContextListener接口的MyServletContextListener標注為監聽器
 9  */
10 @WebListener
11 public class MyServletContextListener implements ServletContextListener {
12 
13     @Override
14     public void contextDestroyed(ServletContextEvent sce) {
15         System.out.println("ServletContex銷毀");
16     }
17 
18     @Override
19     public void contextInitialized(ServletContextEvent sce) {
20         System.out.println("ServletContex初始化");
21         System.out.println(sce.getServletContext().getServerInfo());
22     }
23 }

  Web應用啟動時就會初始化這個監聽器,如下圖所示:

  

  有了@WebListener注解之后,我們的web.xml就無需任何配置了

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

  Servlet3.0規范的出現,讓我們開發Servlet、Filter和Listener的程序在web.xml實現零配置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM