如何在没有Spring引导的情况下使用嵌入式tomcat注册Spring MVC dispatcher servlet?
我的问题与此类似。我想在嵌入式Tomcat上运行Spring MVC Dispatcher Servlet。但我总是以一个异常结束,即WebApplicationObjectSupport实例不在ServletContext中运行。 我的示例只有两个类:如何在没有Spring引导的情况下使用嵌入式tomcat注册Spring MVC dispatcher servlet?,spring,spring-mvc,tomcat,embedded-tomcat-8,Spring,Spring Mvc,Tomcat,Embedded Tomcat 8,我的问题与此类似。我想在嵌入式Tomcat上运行Spring MVC Dispatcher Servlet。但我总是以一个异常结束,即WebApplicationObjectSupport实例不在ServletContext中运行。 我的示例只有两个类: class Application { public static void main(String[] args) throws LifecycleException, ServletException { try
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 dispatcher如何与嵌入式tomcat一起使用,但不需要启动吗?您可以创建一个
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
}
}