JBoss AS 7:通过代码配置将Servlet映射到Context Root("/")

Bre*_*dan 5 java servlets java-ee jboss7.x

使用JBoss AS 7,我正在尝试使用Java代码而不是web.xml来配置我的Servlet 3.0容器.我的问题是,当我注册一个映射到上下文根("/")的Servlet时,默认的servlet优先使用并处理请求.我已经尝试过ServletContextListener和ServletContainerInitializer,但没有运气.

尝试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.
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试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);
    }
}
Run Code Online (Sandbox Code Playgroud)

附加信息

  • 如果我将映射更改//example,我的Servlet会正确处理对新路径的请求.
  • 如果我/通过web.xml而不是Java代码注册我的Servlet ,我的Servlet正确处理对上下文根的请求.

那么......我怎样才能通过Java代码将Servlet注册到上下文根目录而不被DefaultServlet覆盖?

谢谢!

sup*_*rEb 6

我使用JBoss AS 7.1.1和Spring MVC 3.2.3.RELEASE也遇到了同样的问题.基于此来自WebApplicationInitializer的javadocs:

在Tomcat下映射到'/'

Apache Tomcat将其内部DefaultServlet映射到"/",而在Tomcat版本<= 7.0.14上,无法以编程方式覆盖此servlet映射.7.0.15修复了这个问题.覆盖"/"servlet映射也已在GlassFish 3.1下成功测试.

除非servlet容器已升级或替换,否则我认为没有任何方法可以将servlet映射到没有web.xml的上下文根.看起来像JBoss AS 7.1.1.Final使用JBoss Web 7.0.13,我假设它与Tomcat 7.0.13一致,并且在版本7.0.15 plus之前,以编程方式覆盖DefaultServlet上下文根映射显然是不可能的.

在此期间,要么在web.xml中定义servlet映射,要么不映射到上下文根.缺点,第.