I\'m trying to register a servlet using servletContainerInitializer but it doesn\'t seem to work, Maybe it\'s my code (kindly review it), but I came to wonder about the diff
Check if you have configured the ServletContainerInitializer propertly. The ServletContainerInitializer class name should be configured inside a file:
META-INF/services/javax.servlet.ServletContainerInitializer
The file should contain just the class name. For Ex in your case it should look like:
com.marmoush.javaexamples.nullhaus.servlet.MyInit
The file (META-INF/services/javax.servlet.ServletContainerInitializer) can be bundled in a library JAR in WEB-INF/lib.
Here is any example which explains.
The ServletContainerInitializer
implementation is intented to be bundled in a JAR file which is in turn been dropped in /WEB-INF/lib
of the webapp. The JAR file itself should have a /META-INF/services/javax.servlet.ServletContainerInitializer
file containing the FQN of the ServletContainerInitializer
implementation in the JAR. Please note that this file should thus not be placed in the webapp itself!
This allows webapp module developers to let their JAR file hook on webapp's startup and shutdown cycle. It's true that they could also have used a ServletContextListener
with @WebListener
for this, but this won't work if the webapp's own web.xml
file has a metadata-complete="true"
attribute set in <web-app>
which means that the webapp shouldn't scan JARs for annotations (which saves startup time).
That the ServletContainerInitializer
doesn't work in your particular case can only mean that you're actually not developing a module JAR file, but just a part integral to your own web application. In that case, the ServletContainerInitializer
is useless for you and you should be using ServletContextListener
instead.
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// Do stuff during server startup.
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// Do stuff during server shutdown.
}
}