If you want to distribute your code as a JAR file (as opposed to files inside WEB-INF/classes
of a WAR file), a ServletContainerInitializer
is what you need.
This sums up to:
- Creating a class (e.g.
com.example.Initializer
) that implements ServletContainerInitializer
,
- Putting its qualified name into a file
META-INF/services/javax.servlet.ServletContainerInitializer
,
- (Optional) Creating a file
META-INF/web-fragment.xml
with content:
<?xml version="1.0" encoding="UTF-8"?>
<web-fragment 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-fragment_3_0.xsd"
version="3.0" metadata-complete="true">
<name>a_short_name</name>
</web-fragment>
The last step is useful if your users want to enable just a selected set of ServletContainerInitializer
s (using <absolute-ordering>
). Usually all ServletContainerInitializer
s are enabled.
Edit: You can also use a ServletContextListener
as in the question cited by Boug. In this case you don't need step 2, but you need to declare the ServletContextListener
in the web-fragment.xml
file.