Spring MVC视图解析器:配置多个视图解析器的优先级

在SpringMVC中,多个视图解析器可通过order属性设置优先级,order值越小优先级越高。InternalResourceViewResolver通常设为最低优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

在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值),因为不管返回什么视图名称,它都将解析视图。如果它的优先级高于其它解析器的优先级的话,它将使得其它具有较低优先级的解析器没有机会解析视图。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值