原文 http://www.cnblogs.com/oumyye/p/4592253.html 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 |