問題描述:
今天自己在搭建spring、springMVC、hibernate框架,搭建完成后,在引入jquery時,發現jquery不管用。我的解決順序是:
1、檢查路徑,發現路徑沒錯,另外需要注意的是,非rest風格的代碼下,js資源一般為靜態資源,不要放在web-inf下,否則會加載不上,另外注意js編碼是否和當前頁面編碼一致,此處我設置utf-8編碼。
<script src="${pageContext.request.contextPath }/js/jquery-1.4.2.js" charset="utf-8"></script>
2、排錯,我將jquery中代碼直接復制到我的script里,發現是管用的,這至少說明,jquery沒有問題。
3、控制台輸出發現了問題所在:
14:57:55,021 DEBUG DispatcherServlet:823 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/SSH_TEST/js/jquery-1.4.2.js]
14:57:55,022 DEBUG RequestMappingHandlerMapping:209 - Looking up handler method for path /js/jquery-1.4.2.js
14:57:55,023 DEBUG RequestMappingHandlerMapping:219 - Did not find handler method for [/js/jquery-1.4.2.js]
第一句:DispatcherServlet 以get方式請求[/SSH_TEST/js/jquery-1.4.2.js]
第三句:沒有找到
4.解決方法:
我的web.xml文件部分如下
<!-- springMVC核心控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> </servlet>
<!-- map all request to the dispatcherServlet for handling --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
注意,黃色部分屬於rest風格,即dispatcherServlet將處理所有web容器的請求,當請求加載靜態資源jquery.js時,控制器類中沒有寫,因此會提示【Failed to load resource: the server responded with a status of 404 (Not Found)】,如果是傳統的風格,非rest,一般靜態資源時web容器自己就加載了。
處理方法:在springMVC.xml文件添加如下。
<mvc:default-servlet-handler/>