使用SpringMVC正確加載靜態資源文件

初學Springmvc的人都會碰到一個令人頭痛的問題
那就是爲什麼我配置好web.xml中的dispatchservlet後,js,css,甚至gif都不能正常顯示了

我們來看看我們配置的web.xml

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext.xml</param-value>
</context-param>
  
<listener>
  <listener-class>
      org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>
  
<!-- 核心servlet控制器 --> 
<servlet>
    <servlet-name>spring-mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext.xml</param-value>
    </init-param>
</servlet> 

其中url-pattern:

url-pattern有5種配置模式:  

(1)/xxx:完全匹配/xxx的路徑  

(2)/xxx/*:匹配以/xxx開頭的路徑,請求中必須包含xxx。  

(3)/*:匹配/下的所有路徑,請求可以進入到action或controller,但是轉發jsp時再次被攔截,不能訪問jsp界面。

(4).xx:匹配以xx結尾的路徑,所有請求必須以.xx結尾,但不會影響訪問靜態文件。  

(5)/:默認模式,未被匹配的路徑都將映射到刺servlet,對jpg,js,css等靜態文件也將被攔截,不能訪問。 

如果我們一開始就採用了/的方式,那麼就需要補上如下的web.xml配置來讓靜態文件可訪問了。因爲spring mvc默認攔截所有請求,所以你需要單獨把靜態資源配起來,springmvc就會放過這些請求了。

方法一:在web.xml文件中添加xml配置,
  

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
</servlet-mapping>
 
<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.js</url-pattern>
</servlet-mapping>
 
<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
 
    ...   
    ... 


方法二:在applicationContext.xml配置中添加
    先需要開啓mvc的配置
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="...
        http://www.springframework.org/schema/mvc

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

<mvc:default-servlet-handler/>

方法三:  在applicationContext.xml配置中添加

<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/imgs/**" location="/imgs/" /> 


注意:    css,js,images文件夾放於WebContent目錄下。
好了。 

凡是在jsp中需要訪問這些資源的,可以使用

如<link rel="stylesheet" href="<%=request.getContextPath() %>/css/main.css" type="text/css" /> 

以上幾種方法經過測試是可以成功的!
--------------------- 
作者:caychen 
來源:CSDN 
原文:https://blog.csdn.net/caychen/article/details/79625462 
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章