1 在web.xml中使用默認servlet處理靜態資源,缺點是如果靜態資源過多,則配置量會比較大,一旦有遺漏,則會造成資源無法正常顯示或404錯誤。
<!-- 靜態資源訪問控制 --><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.jpg</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.png</url-pattern></servlet-mapping><!-- rest風格的攔截,需進行靜態資源訪問配置 --><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
2 在springmvc配置文件中配置
我的所有靜態資源都在WebContent/static/之下,下有如下目錄WebContent/static/img,WebContent/static/css,WebContent/static/js等等,在springmvc配置文件中添加如下配置,以下兩個配置二選一即可,當然配置兩最小的是第二種了,第一種的優勢在于可以自主定制,可以規定哪些靜態資源是可以訪問的,哪些是不能訪問的。
<!--靜態資源的訪問配置,文件夾配置,二選一 --> <mvc:resources mapping="/static/**" location="/static/" cache-period="31556926"/> <!--靜態資源的訪問配置,文件夾配置,二選一 --> <mvc:default-servlet-handler/>
FAQ:
如果在配置文件中無法使用<mvc:相關的標簽,可能是你未引入xmlns:mvc="http://www.springframework.org/schema/mvc"命名空間,其次spring版本3.0以上,我的是3.0.5版本的,測試可行。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
?