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標注為監聽器 */@WebListenerpublic class MyServletContextListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { System.out.
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.companysz.com/xdp-gacl/p/4226851.html
新聞熱點
疑難解答