springMVC中default-servlet-handler的作用
阿新 • • 發佈:2019-01-04
<mvc:default-servlet-handler/> 這個springMVC xml檔案的屬性,主要是處理web專案的靜態檔案問題。
使用springMVC進行web專案開發的時候,通常在web.xml檔案中會做如下的配置:
使用springMVC進行web專案開發的時候,通常在web.xml檔案中會做如下的配置:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
然後進行springMVC的各項配置以後,啟動專案,在瀏覽器中輸入地址後出現如下問題
正常的頁面顯示成這樣,所有的靜態js,css圖片等都被DispatcherServlet處理後,頁面的樣式沒了。
針對這個問題<mvc:default-servlet-handler/>這個標籤可以幫我們解決這一問題,在springMVC的配置檔案中配置了改xml標籤屬性相當於在dispatcherServlet處理鏈上串聯了一個java:org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler靜態資源處理類,每次請求過來,先經過DefaultServletHttpRequestHandler判斷是否是靜態檔案,如果是靜態檔案,則進行處理,不是則放行交由DispatcherServlet控制器處理。
在springMVC配置檔案中配置如下:
在springMVC配置檔案中進行上述配置後,頁面顯示正常。<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 靜態資源處理servlet配置 --> <mvc:default-servlet-handler/> <mvc:annotation-driven/> </beans>
配置方式二:
通過程式進行配置
@Configuration
@EnableWebMvc
public classWebConfig extendsWebMvcConfigurerAdapter {
@Override
public voidconfigureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//myCustomDefaultServlet這個是在spring中配置的servletBean的名字
configurer.enable("myCustomDefaultServlet");
}
}
上面的這兩種配置方式只是在DispatcherServlet的請求處理路徑為“/”的情況下使用,如果你配置的是*.do或*.pay等方式則不需要上面這樣的配置,因為*.do或*.pay只處理以它結尾的請求,對靜態資原始檔不會做任何處理。