Spring 3,AbstractAnnotationConfigDispatcherServletInitializer,多个servlet

时间:2013-05-16 20:42:53

标签: spring servlet-3.0

使用Servlet 2.5,可以通过简单地复制和编辑以下xml标记来使用web.xml文件中配置的多个servlet。

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

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

使用Spring的AbstractAnnotationConfigDispatcherServletInitializer与Servlet 3创建多个servlet是否可行?

我认为在getServletConfigClasses()方法中返回2个类,在getServletMappings()方法中返回2个路径就足够了,但这并不像我预期的那样工作。

那么,有没有(简单)方法使用Spring 3和Servlet 3配置多个servlet?

感谢您的回答!

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {

      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

     ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");

     ServletRegistration.Dynamic anotherServlet =
        container.addServlet("anotherServlet", "com.xxx.AnotherServlet");
      anotherServlet.setLoadOnStartup(2);
      anotherServlet.addMapping("/another/*");

     ServletRegistration.Dynamic yetAnotherServlet =
        container.addServlet("yetAnotherServlet", "com.xxx.YetAnotherServlet");
      yetAnotherServlet.setLoadOnStartup(3);
      yetAnotherServlet.addMapping("/yetanother/*");

    }

 }

当然,您可以根据自己的方便使用任何addServlet()方法。