jsp不能引用js,cs等解決辦法

來源:互聯網
上載者:User

標籤:

最近項目中使用到Spring3,在感歎Spring3註解配置清爽的同時竟然出現了這個不和諧的事情,實在無法忍受

問題:部署項目後程式載入或用瀏覽器訪問時出現類似的警告,2011-01-19 10:52:51,646 WARN [org.springframework.web.servlet.PageNotFound] -<No mapping found for HTTP request with URI [/sandDemo001/images/1.jpg] in DispatcherServlet with name ‘spring‘>,主要看角括弧內部分。

問題原因:罪魁禍首是web.xml下對spring的DispatcherServlet請求url映射的配置,原配置如下:

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
 </servlet-mapping>

分析原因:<servlet-mapping>的<url-pattern>/</url-pattern>把所有的請求都交給spring去處理了,而所有available的請求url都是在Constroller裡使用類似@RequestMapping(value = "/login/{user}", method = RequestMethod.GET)這樣的註解配置的,這樣的話對js/css/jpg/gif等靜態資源的訪問就會得不到。

解決方案:在web.xml裡添加如下的配置

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

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

解決方案2:在spring的設定檔中添加如下一行:

<mvc:default-servlet-handler/>

注意,需要是spring3.0.5以上版本

解決方案3

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
 
 <mvc:resources mapping="/resources/**" location="/resources/" />  例如:  
  <!-- For static resources -->    <mvc:resources mapping="/image/**" location="/images/" />    <mvc:resources mapping="/js/**" location="/js/" />    <mvc:resources mapping="/css/**" location="/css/" />    <mvc:resources mapping="/html/**" location="/html/" />    <mvc:resources mapping="/software/**" location="/software/" />  

  下面這種是直接根據靜態檔案的尾碼來配置的,比較通用,不用為每個子目錄配置一個:
<mvc:resources location="/" mapping="/**/*.html"/><mvc:resources location="/" mapping="/**/*.js"/><mvc:resources location="/" mapping="/**/*.css"/><mvc:resources location="/" mapping="/**/*.png"/><mvc:resources location="/" mapping="/**/*.gif"/>

  
這個配置告訴spring 靜態資源的處理方式 最好還是web.xml 中 "/"路徑寫為*.htm 等

jsp不能引用js,cs等解決辦法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.