「这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战」
概述
这个功能搞了半天没搞成功,现边梳理边调试。 首先上项目路径:
1、首先看一下配置文件 web.xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2、spring的配置文件
2.1 方式一
<?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" xmlns:mvn="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 https://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.zhl"></context:component-scan>
<!--配置访问静态资源 -->
<mvc:annotation-driven/>
<!-- 将映射的地址直接指向静态资源文件夹,springmvc将不会将此映射作为handler
mapping : 访问静态资源的路径
location : 静态资源存储目录 如果静态资源在根目录下,要如何访问呢?
-->
<mvn:resources mapping="/html/**" location="/html/"/>
</beans>
这种方式,只能访问html文件夹下的main.html。无法访问根目录下的main.html。
2.2 方式二
<?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" xmlns:mvn="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 https://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.zhl"></context:component-scan>
<!--配置访问静态资源 -->
<mvc:annotation-driven/>
<!--当springmvc 没有映射到某一个请求的时候, 就会调用默认servlet处理-->
<mvc:default-servlet-handler/>
</beans>
这种方式既能访问根目录下所有的静态资源都能访问。