您的位置:首页 > 编程语言 > Java开发

Spring MVC配置多个视图解析器(FreeMarker,JSP)

2013-05-11 21:08 344 查看
Spring MVC配置多个视图解析器(FreeMarker,JSP)

Spring MVC开发过程中,有时候需要多个视图解析器策略来解析视图名称,出现这个情况怎么解决?

通过“order”属性来声明优先级,order值越低,则优先级越高。例如:

<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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自动扫描com.baobaotao.web 包下的@Controller标注的类控制器类 -->
<context:component-scan base-package="com.feng.web" />

<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<mvc:annotation-driven/>

<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<!-- FreeMarker基础设施及视图解析器配置 -->
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
p:templateLoaderPath="/WEB-INF/ftl" p:defaultEncoding="UTF-8">
<property name="freemarkerSettings">
<props>
<prop key="classic_compatible">true</prop>
</props>
</property>
</bean>

<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
p:order="0" p:suffix=".ftl" p:contentType="text/html; charset=utf-8" />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="1" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" />

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="i18n/messages" />

<!--WEB异常解析处理-->
<bean id="exceptionResolver" class="com.baobaotao.web.ForumHandlerExceptionResolver">
<property name="defaultErrorView">
<value>fail</value>
</property>
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">fail</prop>
</props>
</property>
</bean>
</beans>


注意:

1:InternalResourceViewResolver必须赋予给最低的优先级(最大的order值),因为不管返回什么视图名称,它都将解析视图。如果它的优先级高于其它解析器的优先级的话,它将使得其它具有较低优先级的解析器没有机会解析视图。

2:如果Controller中返回视图加了后缀jsp或者ftl,在配置中就不要加入suffix配置,否则会找不到页面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: