JBoss AS 7: Map Servlet to Context Root ("/") via Code Config
jakarta-ee, java, jboss7.x, servlets
Solution
I had the same problem using JBoss AS 7.1.1 and Spring MVC 3.2.3.RELEASE. Based on this from the WebApplicationInitializer javadocs:
Mapping to '/' under Tomcat
Apache Tomcat maps its internal DefaultServlet to "/", and on Tomcat versions <= 7.0.14, this servlet mapping cannot be overridden programmatically. 7.0.15 fixes this issue. Overriding the "/" servlet mapping has also been tested successfully under GlassFish 3.1.
I don't think there's any way to map your servlet to the context root without a web.xml unless the servlet container is either upgraded or replaced. Looks like JBoss AS 7.1.1.Final uses JBoss Web 7.0.13, which I assume aligns with Tomcat 7.0.13, and programmatically overriding the DefaultServlet context root mapping is apparently impossible until version 7.0.15 plus.
In the meantime, either define your servlet mapping in web.xml or don't map to the context root. Bummers.
Problem
Using JBoss AS 7, I'm trying to configure my Servlet 3.0 container using Java code instead of a web.xml. My problem is that when I register a Servlet mapped to the context root ("/"), the default servlet is taking precedence and handling requests instead. I've tried both ServletContextListener and ServletContainerInitializer with no luck. Attempt 1: ServletContextListener ``` @WebListener public class AppInitializer implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); ServletRegistration.Dynamic homeServlet = context.addServlet("homeServlet", new HomeServlet()); homeServlet.addMapping("/"); homeServlet.setLoadOnStartup(1); } @Override public void contextDestroyed(ServletContextEvent event) { // Do nothing. } } ``` Attempt 2: ServletContainerInitializer ``` public class AppInitializer2 implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> classes, ServletContext context) throws ServletException { ServletRegistration.Dynamic homeServlet = context.addServlet("homeServlet", new HomeServlet()); homeServlet.addMapping("/"); homeServlet.setLoadOnStartup(1); } } ``` Additional Information - If I change the mapping from `/` to `/example`, my Servlet handles requests to the new path correctly. - If I register my Servlet to `/` via web.xml instead of Java code, my Servlet handles requests to the context root correctly. So… what can I do to register a Servlet to the context root via Java code without it being overridden by the DefaultServlet? Thanks!