1. 程式人生 > >關於spring 3.0.5的 標籤的使用

關於spring 3.0.5的 標籤的使用

spring mvc 的<mvc;resources mapping="***" location="***">標籤是在spring3.0.4出現的,主要是用來進行靜態資源的訪問。在spring3.0.4出來的時候spring還沒有更新其schema所以在配置檔案中有可能找不到<mvc:resources >標籤,這個問題在spring3.0.5中已經解決,而且網上也有很多其他的解決方案,我在這裡就不記錄了。

首先使用spring mvc需要配置其使用的servlet.在web.xml中:
Java程式碼  收藏程式碼
  1. <servlet>  
  2.     <servlet-name>springMVC</servlet-name>  
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  4.     <load-on-startup>1</load-on-startup>  
  5.     </servlet>  
  6.     <servlet-mapping>  
  7.         <servlet-name>springMVC</servlet-name>  
  8.         <url-pattern>/</url-pattern>  
  9.     </servlet-mapping>  

這裡給 servlet-name定義的名稱是springMVC,這樣的話會在web-inf下spring會自動掃描一個XML檔名叫springMVC-servlet.xml檔案,這裡都是spring自動掃描的,如果你沒有提供,將會報一個檔案查詢不到的異常。看了下org.springframework.web.servlet.DispatcherServlet載入這個檔案的過程,貌似這個檔案存放的地址也是可以進行設定的,具體怎麼搞我還沒有研究。

由於spring mvc攔截了所有請求,所以當你設定
引用 <servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
的時候會影響到靜態資原始檔的獲取,這樣就需要有這個標籤來幫你分類完成獲取靜態資源的責任。

springMVC-servlet.xml檔案
Java程式碼  收藏程式碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  6.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">   
  7.     <mvc:resources mapping="/javascript/**" location="/static_resources/javascript/"/>  
  8.     <mvc:resources mapping="/styles/**" location="/static_resources/css/"/>  
  9.     <mvc:resources mapping="/images/**" location="/static_resources/images/"/>  
  10.     <mvc:default-servlet-handler />  
  11.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  12.         <property name="prefix" value="/WEB-INF/views/"/>  
  13.         <property name="suffix" value=".jsp"/>  
  14.     </bean>  
  15. </beans>  

這裡可以看到我所有的頁面引用到/styles/**的資源都從/static_resources/css裡面進行查詢。

頁面的一段靜態資源訪問的程式碼。
Java程式碼  收藏程式碼
  1. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>  
  2. <HTML>  
  3. <HEAD>  
  4.   <TITLE> ABCDEFG </TITLE>  
  5. <link type="text/css" rel="stylesheet" href="<c:url value='/styles/siteboard.css'/>">  
  6. ...  
  7. ...  
  8. ...  


可能這個標籤的真諦就是為了引用資源的訪問不會類似CONTROLLER一樣被攔截,區分出關注的資源的訪問,一般我們在springMVC裡面的攔截都會配置為"/",攔截所有的。