How to register multiple servlets in WebApplicationInitializer programatically?

1.4k views Asked by At

I wrote the below class to register multiple servlets programmatically but it is not working can any one help me on this.

public class appIntializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext context) throws ServletException {
        XmlWebApplicationContext appCtxt = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/MVCLogin-servlet.xml");
        context.addListener(new ContextLoaderListener(appCtxt));

        ServletRegistration.Dynamic dispatcher = context.addServlet("MVC",
                new DispatcherServlet(appCtxt));
        ServletRegistration.Dynamic testServlet= context.addServlet(
                "Test", TestServlet.class);
        testServlet.addMapping("/test");

        Dynamic securityFilter = context.addFilter(
                AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME,
                DelegatingFilterProxy.class);
        securityFilter.addMappingForUrlPatterns(
                EnumSet.allOf(DispatcherType.class), false, "/*");
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

    }
}

I should load both the servlets on web application initialization.

1

There are 1 answers

0
Gowtham Murugesan On

I missed out setLoadonstartup that was the issue.

public class appIntializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext context) throws ServletException {
    XmlWebApplicationContext appCtxt = new XmlWebApplicationContext();
    appContext.setConfigLocation("/WEB-INF/MVCLogin-servlet.xml");
    context.addListener(new ContextLoaderListener(appCtxt));

    ServletRegistration.Dynamic dispatcher = context.addServlet("MVC",
            new DispatcherServlet(appCtxt));
    ServletRegistration.Dynamic testServlet= context.addServlet(
            "Test", TestServlet.class);
    testServlet.setLoadOnStartup(2);
    testServlet.addMapping("/test");

    Dynamic securityFilter = context.addFilter(
            AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME,
            DelegatingFilterProxy.class);
    securityFilter.addMappingForUrlPatterns(
            EnumSet.allOf(DispatcherType.class), false, "/*");
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}}