問題
在Spring MVC應用程序中,我們經常需要應用一些視圖解析器策略來解析視圖名稱。例如,聯合使用三個視圖解析器:InternalResourceViewResolver、ResourceBundleViewResolver和XmlViewResolver。
但是,如果返回了一個視圖的名稱,那麼,使用哪一個視圖解析器策略?
解決方法
如果應用了多個視圖解析器策略,那麼就必須通過“order”屬性來聲明優先級,order值越低,則優先級越高。例如:
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
33
34
35
36
37
38
39
40
|
<?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:p= "http://www.springframework.org/schema/p" 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-3.0.xsd http: //www.springframework.org/schema/context http: //www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--
掃描web包,應用Spring的註解 --> <context:component-scan
base- package = "com.xxx.training" /> <bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver" > <property
name= "basename" > <value>spring-views</value> </property> <property
name= "order" value= "0" /> </bean> <bean class = "org.springframework.web.servlet.view.XmlViewResolver" > <property
name= "location" > <value>/WEB-INF/spring-views.xml</value> </property> <property
name= "order" value= "1" /> </bean> <bean
id= "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" > <property
name= "prefix" > <value>/WEB-INF/pages/</value> </property> <property
name= "suffix" > <value>.jsp</value> </property> <property
name= "order" value= "2" /> </bean> </beans> |
注意:InternalResourceViewResolver必須總是賦予最低的優先級(最大的order值),因爲不管返回什麼視圖名稱,它都將解析視圖。如果它的優先級高於其它解析器的優先級的話,它將使得其它具有較低優先級的解析器沒有機會解析視圖。