首页 文章

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

提问于
浏览
3

我的问题类似于这个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

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

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

相关问题