<mvc:default-servlet-handler/> 这个springMVC xml文件的属性,主要是处理web项目的静态文件问题。
使用springMVC进行web项目开发的时候,通常在web.xml文件中会做如下的配置:
使用springMVC进行web项目开发的时候,通常在web.xml文件中会做如下的配置:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
然后进行springMVC的各项配置以后,启动项目,在浏览器中输入地址后出现如下问题
正常的页面显示成这样,所有的静态js,css图片等都被DispatcherServlet处理后,页面的样式没了。
针对这个问题<mvc:default-servlet-handler/>这个标签可以帮我们解决这一问题,在springMVC的配置文件中配置了改xml标签属性相当于在dispatcherServlet处理链上串联了一个java:org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler静态资源处理类,每次请求过来,先经过DefaultServletHttpRequestHandler判断是否是静态文件,如果是静态文件,则进行处理,不是则放行交由DispatcherServlet控制器处理。
在springMVC配置文件中配置如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 静态资源处理servlet配置 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
在springMVC配置文件中进行上述配置后,页面显示正常。
配置方式二:
通过程序进行配置
@Configuration
@EnableWebMvc
public classWebConfig extendsWebMvcConfigurerAdapter {
@Override
public voidconfigureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//myCustomDefaultServlet这个是在spring中配置的servletBean的名字
configurer.enable("myCustomDefaultServlet");
}
}
上面的这两种配置方式只是在DispatcherServlet的请求处理路径为“/”的情况下使用,如果你配置的是*.do或*.pay等方式则不需要上面这样的配置,因为*.do或*.pay只处理以它结尾的请求,对静态资源文件不会做任何处理。