SpringMVC访问静态资源
1.存在的问题
xml中注释掉MVC
效果大概是这样的:
开启mvc框架后:
样式丢失
直接在浏览器中访问css文件,会报错:
2.造成原因
在Tomcat配置文件中,默认有一个servlet对所有请求进行预处理,此时我们配置了DispatcherServlet来进行所有请求的处理,所以Tomcat中默认的servlet不会进行工作,造成资源访问失败
TomCat/conf/web.xml配置
解决办法是:
- 修改自己DispatcherServlet的请求拦截地址,
- 或者在DispatcherServlet处理完请求后再转交给TomCat
- 直接使用Spring MVC 团队自己开发的 处理静态资源的处理器
3.具体解决
1.修改DispatcherServlet拦截路径
然后在浏览器中输入地址及显示结果:
2.处理完后转交tomcat
在spring的配置文件中配置mvc:default-servlet-handler,名字为tomcat中默认的default,在其他服务器可能默认名字不一致
配置文件:
<?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">
<!--将controller扫描到spring容器中-->
<context:component-scan base-package="com.example.controller"></context:component-scan>
<!--开启mvc驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--设置视图解析-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--转交给tomcat的srevlet-->
<mvc:default-servlet-handler default-servlet-name="default"></mvc:default-servlet-handler>
</beans>
3. 使用Spring MVC 的静态资源处理器
它的好处是可以访问类路径下的资源文件,支持classpath
<?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">
<!--将controller扫描到spring容器中-->
<context:component-scan base-package="com.example.controller"></context:component-scan>
<!--开启mvc驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--设置视图解析-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--<mvc:default-servlet-handler ></mvc:default-servlet-handler>-->
<!--使用springMvc自带的静态资源管理器-->
<mvc:resources mapping="/**" location="css"></mvc:resources>
</beans>
类路径写法:<mvc:resources mapping="/css/**" location="classpath:com/css"></mvc:resources>
两种方式中mapping表达的意思不一致