2016-12-27 71 views
0

我寫了下面的類來以編程方式註冊多個servlet,但它不起作用,任何人都可以幫助我解決這個問題。如何以編程方式在WebApplicationInitializer中註冊多個servlet?

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

    } 
} 

我應該在Web應用程序初始化時加載這兩個servlet。

+0

什麼不起作用。 –

+0

我在初始化期間無法加載servlet –

+1

您只在啓動時加載1個servlet。 –

回答

1

我錯過了setLoadonstartup這個問題。

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

}} 
相關問題