Spring MVC 配置启用

Spring MVC configuration enable

我正在从头开始建立一个项目,目前我正在使用 java 配置来配置 Spring MVC 4.1.5。整个应用程序在 tomcat gradle 插件上 运行。

有人能解释一下为什么我需要对 class DefaultServletHandlerConfigurer 进行以下调用才能将请求映射到我的控制器吗?

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

没有启用它,我的所有请求都被拒绝,服务器说没有针对特定请求的映射。

我阅读 spring doc 以了解情况,但描述并没有告诉我太多信息。

Enable forwarding to the "default" Servlet. When this method is used the DefaultServletHttpRequestHandler will try to auto-detect the "default" Servlet name. Alternatively, you can specify the name of the default Servlet via enable(String).

在 Spring MVC 部分文档 here 中对此有很好的解释。

This allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container’s default Servlet), while still allowing static resource requests to be handled by the container’s default Servlet. It configures a DefaultServletHttpRequestHandler with a URL mapping of "/**" and the lowest priority relative to other URL mappings.

This handler will forward all requests to the default Servlet. Therefore it is important that it remains last in the order of all other URL HandlerMappings. That will be the case if you use or alternatively if you are setting up your own customized HandlerMapping instance be sure to set its order property to a value lower than that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.

那段代码相当于 Spring Web MVC 特定组件文件中的 xml 行 <mvc:default-servlet-handler/> 通常定义为 servletname-servlet.xml

您必须使用该调用才能配置转发到 Spring 默认 Servlet,如果您不这样做,您的服务器将尝试使用他自己的 servlet 处理,正如您所解释的,如果您没有任何具体定义,它不会为您的请求找到任何映射。