springmvc静态资源处理

为什要处理静态资源呢?

因为我们使用了springmvc框架,springmvc框架的流程我们都知道,它的核心控制器(dispacherSerlet)拦截所有url,

通过组件handlerMapping的映射使访问的url和对应的controller(adapterHandler,我们写的控制器)匹配,而jsp或者html

中的静态资源,例如图片,css,js,jq等,他们不需要通过控制器处理也被拦截了,就会导致jsp页面找不到图片资源,css

样式等资源加不进来,甚至jsp页面会报错。所以我们务必要处理静态资源。接下来我们来演示如何处理静态资源。


一般项目资源放到WebRoot下?______谁回答下。

静态资源的处理有三种方式。

1,servlet提供的,在web.xml下配置,name标签固定的值是default,url是匹配对应静态资源的,这里们匹配所有带有.png后缀的资源,你可以写多个,根据需要。

一定要注意,这个静态资源的配置要写在dispatcherServlet前面。这种写法不是很灵活,但是效率要快些。

<!--性能好-->

<servlet-mappping>

<servlet-name>default</servlet-name>

<url-pattern>*.png</url-pattern>

</servlet-mapping>

2,spring提供的,在springmvc的xml下配置,location是静态资源定位,mapping的写法就是处理这个定位资源下的所有资源。

 <!-- 灵活但性能差一些 -->

<mvc:annotation-driven />

<mvc:resources location="/static/" mapping="/static/**" />

3,srping提供的,在springmvc.xml下配置,不推荐使用它是扫描所有controller资源的url和本次访问一个一个的比较,如果controller中不存在就视为静态资源处理。

<!--性能不好-->

<mvc:default-servlet-handler/>hk


mvc标签命名空间的引用---

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

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:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="

http://www.springframework.org/schema/beans 

 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

 http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

 http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

 http://www.springframework.org/schema/mvc

 http://www.springframework.org/schema/mvc/spring-mvc.xsd

">

 </beans>

学习使我快乐! 一起成长
原文地址:https://www.cnblogs.com/zhizhuoDEZHUZHU/p/9618336.html