Is it necessary to make listener-class tag entry in web.xml even after adding @WebListener annotation to my listener class?
Because when I use just @WebListener annotation without making listener-class tag entry in web.xml, my listener class does not get executed.
When I use both the listener-class tag entry in web.xml and @WebListener for my listener class, then only my listener class is getting executed.
(Additional info: java version "1.7.0_79" , Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Following is the listener-class tag entry in web.xml :
<listener>
<listener-class> org.shan.jspservlets.CountUserListener </listener-class>
</listener>
Following is my 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);
}
}
Annotations like @WebServlet
, @WebListener
, etc. were introduced in Servlet 3.0, so if you are using a servlet container with a servlet version < 3.0 the annotations are not processed.
Annotations are also not processed if the web-app
element tells the container to ignore them:
<web-app metadata-complete="true" ...>
Then your annotated class must be either in WEB-INF/classes
or in a jar in WEB-INF/lib
, else the annotation is also ignored.