一、介绍
(1)如果项目的web.xml文件中配置了DispatcherServlet且其url-pattern为缺省匹配,则会覆盖Tomcat中的DefaultServlet配置,此时SpringMVC不能根据请求路径找到对应的静态资源并返回给浏览器。
(2)SpringMVC提供了<mvc:default-servlet-handler/>
标签。在SpringMVC配置文件中声明该标签后,当DispatcherServlet根据请求找不到对应的方法执行时,会将请求交给DefaultServlet处理。
二、项目测试
(1)在webapp下创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>index</h1>
</body>
</html>
(2)编写SpringMVC-config.xml文件,通过声明<mvc:default-servlet-handler/>
标签来使SpringMVC具有处理静态资源的能力
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.wsh.controller"></context:component-scan>
<!-- 配置Thymeleaf视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<!--视图解析器优先级-->
<property name="order" value="1"/>
<!--解析视图用的编码-->
<property name="characterEncoding" value="UTF-8"/>
<!--视图解析器模板引擎-->
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!--视图前缀-->
<property name="prefix" value="/WEB-INF/templates/"/>
<!--视图后缀-->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<mvc:default-servlet-handler/>
</beans>
(3)运行