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


問題

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

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

解決方法

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

<?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值),因為不管返回什么視圖名稱,它都將解析視圖。如果它的優先級高於其它解析器的優先級的話,它將使得其它具有較低優先級的解析器沒有機會解析視圖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM