我相信这是因为Tomcat。网络上的大多数教程都将 spring mvc servlet 直接放在应用程序上下文中。它从来没有对我有用。
在 Tomcat7 上(即使使用 XML 配置),您必须创建两个上下文:一个用于整个应用程序,另一个用于 spring web mvc。这与
@RequestMapping("/")
服务器将“/”映射分配给默认的内置servlet。这是您希望他(或它或她)做的事情。但你还需要 Spring MVC 来映射“/”。
也许他们(架构师)认为 springmvc 是一个特定的 servlet,不应该映射根上下文。相反,它应该在他自己的映射下(例如“/springmvc/”)。然后它期望我们有一个真正的调度程序......在 springmvc 和任何其他 servlet 之间进行调度。
由于某些神奇的原因,在 Tomcat 7.0.29 中,如果您尝试劫持“/”,它甚至无法“调度”。在最新版本中,映射“/”是可行的。但是为此您需要一个单独的 Web mvc 上下文/根上下文。
我不使用 AbstractAnnotationConfigDispatcherServletInitializer 你必须翻译下面的代码。
这是改编自有关从 XML 迁移到 Javaconfig 的教程spring-app-migration-从-xml-to-java-based-config
public class WebInit implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_NAME = "spring-mvc";
private static final String DISPATCHER_SERVLET_MAPPING = "/";
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
//If you want to use the XML configuration, comment the following two lines out.
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(CoreConfig.class);
appContext.setDisplayName("removed customer name");
//If you want to use the XML configuration, uncomment the following lines.
//XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
//rootContext.setConfigLocation("classpath:mvc-servlet.xml");
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(ServletConfig.class);
ServletRegistration.Dynamic springmvc =
servletContext.addServlet(DISPATCHER_SERVLET_NAME,
new DispatcherServlet(mvcContext));
springmvc.setLoadOnStartup(1);
springmvc.addMapping(DISPATCHER_SERVLET_MAPPING);
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
servletContext.addListener(new ContextLoaderListener(appContext));
}