如何在没有spring-boot的情况下使用嵌入式tomcat注册Spring MVC调度程序servlet?

时间:2017-01-02 10:49:40

标签: spring spring-mvc tomcat embedded-tomcat-8

我的问题类似于Embedded Tomcat Integrated With Spring。我想在嵌入式Tomcat上运行Spring MVC Dispatcher Servlet。但我总是得到一个例外,说WebApplicationObjectSupport实例不在ServletContext中运行。 我的例子只有两个类:

 class Application {
    public static void main(String[] args) throws LifecycleException, ServletException {
        try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) {
            context.registerShutdownHook();
            context.register(WebConfig.class);
            context.refresh();
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(9090);
            File base = new File("");
            System.out.println(base.getAbsolutePath());
            Context rootCtx = tomcat.addWebapp("", base.getAbsolutePath());
            DispatcherServlet dispatcher = new DispatcherServlet(context);
            Tomcat.addServlet(rootCtx, "SpringMVC", dispatcher);
            rootCtx.addServletMapping("/*", "SpringMVC");
            tomcat.start();
            tomcat.getServer().await();
        }
    }
}


@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/assets/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:index.html");
    }
}

如何通过调用tomcat.addWebApp(..)方法以不同方式定义servlet上下文?有没有人举例说明Spring MVC调度程序如何与嵌入式tomcat一起使用但没有启动?

1 个答案:

答案 0 :(得分:0)

您可以创建ServletContextInitializer并通过@Configuration隐藏它:

@Configuration
class WebAppInitConfig implements ServletContextInitializer {
    @Override
    void onStartup(ServletContext context) {
        AnnotationConfigWebApplicationContext webAppContext = new AnnotationConfigWebApplicationContext()
        webAppContext.register(RootConfig)
        webAppContext.registerShutdownHook()

        ServletRegistration.Dynamic dispatcher = context.addServlet("dispatcher", new DispatcherServlet(webAppContext))
        dispatcher.loadOnStartup = 1
        dispatcher.addMapping("/*")
        // Whatever else you need
    }
}