简体   繁体   English

根据Tomcat上下文更改servlet映射

[英]Change servlet mapping depending on Tomcat context

I'd like to assign a different default servlet when inside a particular Tomcat context. 我想在特定的Tomcat上下文中分配一个不同的默认servlet。

For example, when inside my root context, I want to use the following servlet mapping: 例如,在我的根上下文中时,我想使用以下servlet映射:

  <servlet-mapping>
    <servlet-name>PageServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

But when inside a context located on path /img-data , I want to use: 但是,当位于路径/img-data上的上下文中时,我想使用:

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

Is this possible? 这可能吗?

If your application runs in servlet 3.0+ container you could use a ServletContextListener to dynamically set the default servlet, depending on the context path. 如果您的应用程序在Servlet 3.0+容器中运行,则可以使用ServletContextListener来动态设置默认servlet,具体取决于上下文路径。

public class MyServletContextListener implements ServletContextListener {
    @Override public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        if ("".equals(sc.getContextPath())) {
            ServletRegistration.Dynamic dreg = sc.addServlet("pageservlet", new PageServlet());
            dreg.addMapping("");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM