即使在向我的侦听器 class 添加 @WebListener 注释后,是否有必要在 web.xml 中创建 <listener-class> 标记条目?

Is it necessary to make <listener-class> tag entry in web.xml even after adding @WebListener annotation to my listener class?

是否有必要在 web.xml 中添加 listener-class 标签条目,即使在我的监听器 class 中添加了 @WebListener 注释之后?

因为当我只使用@WebListener 注释而没有在 web.xml 中创建 listener-class 标记条目时,我的监听器 class 不会被执行。

当我在 web.xml 中同时使用 listener-class 标记条目和我的监听器 class 中的 @WebListener 时,只有我的监听器 class 被执行。

(附加信息:java 版本“1.7.0_79”,Java(TM) SE 运行时环境(build 1.7.0_79 -b15)

以下是 web.xml 中的 listener-class 标签条目:

<listener>
        <listener-class>  org.shan.jspservlets.CountUserListener </listener-class>
</listener>

以下是我的听众class:

package org.shan.jspservlets;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class CountUserListener implements HttpSessionListener {
 ServletContext ctx = null;
 static int total = 0, current = 0;

 public void sessionCreated(HttpSessionEvent e) {
  total++;
  current++;

  ctx = e.getSession().getServletContext();
  ctx.setAttribute("totalusers", total);
  ctx.setAttribute("currentusers", current);

 }

 public void sessionDestroyed(HttpSessionEvent e) {
  current--;
  ctx.setAttribute("currentusers", current);
 }

}

@WebServlet@WebListener 等注释是在 Servlet 3.0 中引入的,因此如果您使用的 servlet 容器的 servlet 版本低于 3.0,则不会处理注释。

如果 web-app 元素告诉容器忽略注释,注释也不会被处理:

<web-app metadata-complete="true" ...>

那么你的注释 class 必须在 WEB-INF/classes 中或在 WEB-INF/lib 中的 jar 中,否则注释也会被忽略。