Default Servlet

Spring MVC允许将DispatcherServlet映射到/(从而覆盖容器默认Servlet的映射),同时仍允许容器的默认Servlet处理静态资源请求。它配置一个DefaultServletHttpRequestHandler,其URL映射为**/,并且相对于其他URL映射其优先级最低。

Spring MVC 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.

此处理程序将所有请求转发到默认Servlet。因此,它在所有其他URL HandlerMapping中必须保持为最后一个。如果你使用<mvc:annotation-driven>,便是如此。或者,如果你设置自己的定制HandlerMapping实例,请务必将它的order属性设置为低于DefaultServletHttpRequestHandler(即Integer.MAX_VALUE)的值。

This handler forwards all requests to the default Servlet. Therefore, it must remain last in the order of all other URL HandlerMappings. That is the case if you use <mvc:annotation-driven>. Alternatively, if you set 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.

以下示例显示如何使用默认设置启用此功能:

The following example shows how to enable the feature by using the default setup:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

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

覆盖/Servlet映射唯一的注意事项是,必须按名称而不是按路径检索默认Servlet的RequestDispatcher。DefaultServletHttpRequestHandler尝试在启动时间自动检测容器的默认Servlet,使用已知的大多数主要Servlet容器(包括Tomcat、Jetty、GlassFish、JBoss、Resin、WebLogic和WebSphere)的名称列表。如果默认Servlet已使用其他名称自定义配置,或者使用的是默认Servlet名称未知的不同Servlet容器,那么你必须明确提供默认Servlet的名称,如下例所示:

The caveat to overriding the / Servlet mapping is that the RequestDispatcher for the default Servlet must be retrieved by name rather than by path. The DefaultServletHttpRequestHandler tries to auto-detect the default Servlet for the container at startup time, using a list of known names for most of the major Servlet containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere). If the default Servlet has been custom-configured with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then you must explicitly provide the default Servlet’s name, as the following example shows:

@Configuration
public class CustomDefaultServletConfiguration implements WebMvcConfigurer {

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