学习的博客:http://elf8848.iteye.com/blog/875830/
我项目中所用的版本:4.2.0。博客的时间比较早,11年的,学习的是Spring3 MVC。不知道版本上有没有变化比较大的功能。
spring mvc教程(七)多视图控制器
1.多视图控制器的配置
当有jsp,flt等多种页面生成展示方式时,spring默认使用"视图解析器链",直到找到对应的"视图解析器"。注意!jsp视图解析器的处理(不是配置是类里面)一定要写在最后,因为一旦调用jsp,就像浏览器发出数据了,视图解析器链就中断了。
示例:(说好的jsp的要写在最后呢???看到后面才发现自己误会了,配置文件中顺序无关,是ViewResolver中。)
<!-- 多视图处理器 -->
<bean class="com.xxx.core.web.MixedViewResolver">
<property name="resolvers">
<map>
<entry key="jsp">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
</bean>
</entry>
<entry key="ftl">
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="contentType" value="text/html;charset=UTF-8"></property>
<!-- 宏命令的支持 -->
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
<property name="requestContextAttribute" value="rc"></property>
</bean>
</entry>
</map>
</property>
</bean>
2.多视图控制器的示例代码
public class MixedViewResolver implements ViewResolver{
private Map<String,ViewResolver> resolvers; public void setResolvers(Map<String, ViewResolver> resolvers) {
this.resolvers = resolvers;
} public View resolveViewName(String viewName,Locale locale) throws Exception{
int n=viewName.lastIndexOf(".");
if(n!=-1){
//取出扩展名
String suffix=viewName.substring(n+1);
//取出对应的ViewResolver
ViewResolver resolver=resolvers.get(suffix);
if(resolver==null){
throw new RuntimeException("No ViewResolver for "+suffix);
}
return resolver.resolveViewName(viewName, locale);
}else{ //jsp的处理放到最后
ViewResolver resolver=resolvers.get("jsp");
return resolver.resolveViewName(viewName, locale);
}
}
}