To summarize the answers of JNL and Ted Goddard:
For ServletContextListener (or other listeners like ServletContextAttributeListener or ServletRequestAttributeListener) that need to be loaded by the servlet container, you need to report this to the container. As described in the API docs , there are three ways to do this:
1) Declare it in the deployment descriptor (web.xml):
<listener> <listener-class> com.kyrogaming.AppServletContextListener </listener-class> </listener>
2) or annotate its @WebListener class (see "Annotation Note" below)
3) or register it programmatically using methods in ServletContext, such as addListener () .
Annotation note
Method 1) and 3) will always work. For method 2) (annotations) to work, the servlet container must be configured to scan classes in the classpath to find classes of annotated listeners.
Custom webapp classes (under WEB-INF/classes ) will always be checked, so annotated classes will always be found. However, libraries (JARs under WEB-INF/lib ) will not be checked if web.xml contains the metadata-complete="true" attribute (the default is false ). See Java Servlet Specification Version 3.0 , Chapter 8, “Annotations and Connectivity”.
So, so that the container can find annotated classes in the JAR, make sure that web.xml sets metadata-complete="false" or doesn't set it at all.
Please note that this may delay the launch of the application; see, for example, What to do with annotations after setting metadata-complete = "true" (which allowed Tomcat 7 to start slowly)? .
Unfortunately, this still does not explain why the ServletContextListener in the question is not loaded. Note that web.xml in the question does not matter metadata-complete , which means that it defaults to false , so class scanning is enabled. There may be other problems; this checklist will hopefully help you find it.
sleske
source share