Servlet使用注解標注監聽器(Listener)


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

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

  

監聽器的代碼如下:

package me.gacl.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 使用@WebListener注解將實現了ServletContextListener接口的MyServletContextListener標注為監聽器
 */
@WebListener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContex銷毀");
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContex初始化");
        System.out.println(sce.getServletContext().getServerInfo());
    }
}

  

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

  

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

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

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

轉自:http://www.cnblogs.com/xdp-gacl/p/4226851.html


免責聲明!

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



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