springMVC攔截靜態資源的處理方法
阿新 • • 發佈:2019-01-28
由於web.xml的攔截器配置如下: 應該配置如下:
希望對大家有幫助。。。
<!-- springmvc前臺的控制器 --> <servlet> <servlet-name>taotao-manage</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置檔案預設在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>taotao-manage</servlet-name> <!-- 攔截器“/” 是攔截所有請求,包括靜態資源,所以在springmvc中新增靜態資源對映 --> <!-- <url-pattern>/</url-pattern> --> <url-pattern>/</url-pattern> </servlet-mapping>
<url-pattern>/</url-pattern>配置是攔截所有的請求,包括靜態資源(css,js等。。)
這樣頁面訪問的時候就會沒有效果,解決方案:
- 在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>*.xml</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.swf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.zip</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>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping>
2 在spring.xml中增加配置如下:
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/images/**" location="/images/" />
<resources mapping="/js/**" location="/js/" />
註釋:mapping:對映 location :本地路徑,注意必須是webapp根目錄下的路徑 兩個“**”是資料夾下的所有路徑包含子路徑 如果配置的location在WEB-INF下,準確告訴你還是訪問不到!<!-- 靜態資源對映 讓攔截器放開靜態資源-->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
3 更換過濾器web.xml配置如下:
<servlet>
<servlet-name>springDispatcherServlet</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>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
4 使用預設的配置。下spring.xml中配置如下:<mvc:default-servlet-handler/>
希望對大家有幫助。。。