Spring MVC視圖解析器:配置多個視圖解析器的優先級

原文鏈接:https://www.iteye.com/blog/panyongzheng-2258935

http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836035.html


問題
在Spring MVC應用程序中,我們經常需要應用一些視圖解析器策略來解析視圖名稱。例如,聯合使用三個視圖解析器:InternalResourceViewResolver、ResourceBundleViewResolver和XmlViewResolver。

但是,如果返回了一個視圖的名稱,那麼,使用哪一個視圖解析器策略?

解決方法
如果應用了多個視圖解析器策略,那麼就必須通過“order”屬性來聲明優先級,order值越低,則優先級越高。例如:
Xml代碼

<?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>
  1.  

  注意:InternalResourceViewResolver必須總是賦予最低的優先級(最大的order值),因爲不管返回什麼視圖名稱,它都將解析視圖。如果它的優先級高於其它解析器的優先級的話,它將使得其它具有較低優先級的解析器沒有機會解析視圖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章