1

With Servlet 2.5 it was possible to use multiple servlets configured in the web.xml file by simple duplicating and editing the following xml tags.

<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>

Is it somehow possible to create multiple servlets using Spring's AbstractAnnotationConfigDispatcherServletInitializer with Servlet 3?

I thought that returning 2 classes in getServletConfigClasses() method and 2 paths in getServletMappings() method would be enough, but that doesn't work as I expected it to.

So, is there a (simple) way to configure multiple servlets using Spring 3 and Servlet 3?

Thank you for your answers!

1 Answer 1

1

You can do something like:

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/*");

    }

 }

Ofcourse, You could use any of the addServlet() methods as per your convenience.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I didn't even know the ServletRegistration class. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.