若將DispatcheServlet請求映射設置為/,則SpringMvc將捕獲WEB容器的所有請求,包括靜態資源的請求,SpringMvc會將它們當成一個普通的請求處理,那么將會出現因找不到對應的處理器將導致錯誤。可在SpringMvc的配置中配置<mvc:default-servlet-handler/>的方式解決靜態資源的問題:
-<mvc:default-servlet-handler/>將在SpringMvc上下文中定義一個DefaultServletHttpRequestHandler,它會對進入DispatcheServlet的請求進行篩選,如果發現沒有經過映射的請求,就將該請求交由WEB應用服務器默認的Servlet處理,如果不是靜態資源的請求,才由DispatcheServlet處理。
-一般WEB應用服務器默認的Servlet名稱都是default,若使用的WEB應用服務器的默認Servlet不是default,則需要通過default-servlet-name屬性顯式指定。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?
xml
version="1.0" encoding="UTF-8"?>
<
beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自動掃描的包-->
<
context:component-scan
base-package="com.seven"></
context:component-scan
>
<!--配置視圖解析器,將視圖邏輯名解析為/WEB-INF/pages/<viewName>.jsp-->
<
bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<
property
name="prefix" value="/WEB-INF/pages/"/>
<
property
name="suffix" value=".jsp"/>
</
bean
>
<!--
<mvc:annotation-driven/>在實際開發中都需要配置,而且如果不配置,那么 <mvc:default-servlet-handler/>
就會出問題,老是找不到要訪問的資源。因為這個標簽會自動注冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,
是spring MVC為@Controllers分發請求所必須的。(當然也可以手動配置這兩個bean,但是比較麻煩)
-->
<
mvc:annotation-driven
/>
<
mvc:default-servlet-handler
/>
<!--配置直接轉發的頁面,可以直接轉到相應轉發的頁面,而不用經過handler-->
<!--path屬性是訪問資源時的URL路徑,view-name是資源的視圖名-->
<
mvc:view-controller
path="/success" view-name="hu"/>
<!--
<mvc:resources mapping="/images" location=""/>
這個標簽是為了將訪問資源文件的路徑映射到實際的目錄
-->
</
beans
>
|
