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