自定义一个DispatcherServlet后,访问controller报错Could not open ServletContext resource
时间: 2024-02-01 14:16:22 浏览: 29
这个问题可能是因为在自定义的DispatcherServlet中没有配置正确的ServletContext。可以尝试在自定义的DispatcherServlet中添加如下代码:
```
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setClassLoader(this.getClass().getClassLoader());
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.example.config"); // 配置文件所在的包
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
```
其中,AnnotationConfigWebApplicationContext是基于注解的Spring应用上下文,配置文件所在的包需要根据实际情况修改。另外,在web.xml中也需要配置该自定义的DispatcherServlet。