我相信是因为Tomcat。网络上的大多数教程都将spring mvc servlet直接放在应用程序上下文中。它从来没有为我工作。
在Tomcat7(甚至具有XML配置)上,您必须创建两个上下文:一个用于整个应用程序,一个用于spring web mvc。它与…有关
@RequestMapping("/")服务器将“ /”映射分配给默认的内置servlet。您希望他(或他或她)做这件事。但是,您还需要Spring MVC来映射“ /”。
也许他们(建筑师)认为springmvc是特定的servlet,并且不应该映射根contex。相反,它应该在自己的映射下(例如“ / springmvc
/”)。然后,它期望我们有一个真正的调度程序,可以在springmvc和其他任何servlet之间进行调度。
出于某种神奇的原因,在Tomcat 7.0.29中,如果您试图劫持“ /”,则甚至无法“调度”。在最新版本上,映射“
/”起作用。但是为此,您需要一个单独的Web MVC上下文/根上下文。
我不使用AbstractAnnotationConfigDispatcherServletInitializer,而必须翻译下面的代码。这是从本教程(从XML到Javaconfig的迁移)改编而成的。spring
-app-migration-from-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)); }


