How can I implement this mapping programmatically without web.xml or annotations? The mission is not to use any framework like spring or something else.
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Since Servlet 3.0 you can use
ServletContext#addServlet()
for this.Depending on what you're developing, there are two hooks where you can run this code.
If you're developing a publicly reusable modular web fragment JAR file such as existing frameworks like JSF and Spring MVC, then use a
ServletContainerInitializer
.Or, if you're using it as an internally integrated part of your WAR application, then use a
ServletContextListener
.You only need to make sure that your
web.xml
is compatible with Servlet 3.0 or newer (and thus not Servlet 2.5 or older), otherwise the servletcontainer will run in fallback modus complying the declared version and you will lose all Servlet 3.0 features.See also: