5

使用 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.
    }
}

尝试 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);
    }
}

附加信息

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

So… what can I do to register a Servlet to the context root via Java code without it being overridden by the DefaultServlet?

Thanks!

4

1 回答 1

6

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.

于 2013-06-01T20:31:35.183 回答