SpringMVC同时支持多视图(JSP,Velocity,Freemarker等)的一种思路实现

第一种方式:

在基于SpringMVC的项目中有时需要同时使用多种视图格式,如jsp,velocity及freemarker等,通过不同的请求路径配置规则,映射到不同的视图文件。下面我提供一种思路,通过视图模板文件后缀名的方式来进行处理。例如:

@RequestMapping(value = "/hello") 
public String jspTest(HttpServletRequest request, ModelMap map) { 
    return "demo.jsp"; 

将通过”demo.jsp”的后缀自动使用jsp的视图解析器。

 

下面描述下详细思路:

 

一.自定义视图解析器

复制代码
package com.jeedev.common.web.springmvc.view;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * 自定义视图解析(通过配置实现多视图整合,如jsp,velocity,freemarker,pdf,excel...)
 * @author huligong
 *
 */
public class JeeDevViewResolver implements ViewResolver  {
    
    private static Log logger = LogFactory.getLog(JeeDevViewResolver.class);

    public View resolveViewName(String viewName, Locale locale) throws Exception {
       for(Map.Entry, ViewResolver> map : viewResolverMap.entrySet()){
           Set suffixs = map.getKey();
           for(String suffix : suffixs){
               if (viewName.endsWith(suffix)){
                   ViewResolver viewResolver = map.getValue();
                   if(null != viewResolver){
                       if (logger.isDebugEnabled()) {
                            logger.debug("found viewResolver '" + viewResolver + "' for viewName '" + viewName+ "'");
                        }
                       return viewResolver.resolveViewName(viewName, locale);
                   }
               }
           }
       }
       
       if(defaultViewResolver != null){
           return defaultViewResolver.resolveViewName(viewName, locale);
       }
       // to allow for ViewResolver chaining
       return null;
    }
    
    
    private Map,ViewResolver> viewResolverMap = new HashMap,ViewResolver>();
    
    private ViewResolver defaultViewResolver = null;

    public Map, ViewResolver> getViewResolverMap() {
        return viewResolverMap;
    }

    public void setViewResolverMap(Map, ViewResolver> viewResolverMap) {
        this.viewResolverMap = viewResolverMap;
    }

    public ViewResolver getDefaultViewResolver() {
        return defaultViewResolver;
    }

    public void setDefaultViewResolver(ViewResolver defaultViewResolver) {
        this.defaultViewResolver = defaultViewResolver;
    }
}
复制代码

在自定义视图解析器(其实是视图中转器)中,通过对视图文件的后缀判断(而不是请求地址的后缀)而返回给不同的视图解析器处理。

 

二.视图映射配置dispather-servlet.xml

 

复制代码
<bean id="viewResolver" class="com.jeedev.common.web.springmvc.view.JeeDevViewResolver">
        <property name="defaultViewResolver" ref="beanNameViewResolver"/>
        <property name="viewResolverMap">
            <map>
                <entry>
                    <key>
                        <set>
                            <value>.jspvalue>
                        set>
                    key>
                    <ref bean="jspViewResolver"/>
                entry>
                <entry>
                    <key>
                        <set>
                            <value>.vmvalue>
                            <value>.htmvalue>
                        set>
                    key>
                    <ref bean="velocityViewResolver"/>
                entry>
                <entry>
                    <key><value>.ftlvalue>key>
                    <ref bean="freeMarkerViewResolver"/>
                entry>
            map>
        property>
    bean>

    
    <bean id="beanNameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
    
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
    bean>
    
    
    <bean id="velocityViewResolver" class = "org.springframework.web.servlet.view.velocity.VelocityViewResolver">
         <property name="order" value="0" />
         <property name="contentType" value="text/html;charset=UTF-8" />
         <property name="requestContextAttribute" value="req"/>
    bean>

         
    <bean id="velocityConfig" class = "org.springframework.web.servlet.view.velocity.VelocityConfigurer">
         <property name="configLocation" value="/WEB-INF/velocity.properties"/>
         <property name="resourceLoaderPath" value="/" />
    bean>
    
    
    <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="order" value="0" />
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>  
    bean> 
    
    
         
    <bean id="freemarkerConfig"  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
       <property name="configLocation" value="/WEB-INF/freemarker.properties"/>
        <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>  
         <property name="freemarkerVariables">
             <map>
                <entry key="xml_escape" value-ref="fmXmlEscape"/>
            map>
         property>
    bean>   
    
    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
复制代码

这里我配置成所有返回.jsp的视图模板请求都转到JSP视图解析器jspViewResolver中去处理,返回.htm,.vm视图模板请求都转到velocity视图解析器中去处理。

 

三.控制器代码示例

 

复制代码
package com.jeedev.demo.view;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 多视图解析器支持示例
 * @author huligong
 *
 */
@Controller
@RequestMapping(value = "/demo")
public class JeeDevViewResolverTestController {
    private static Log logger = LogFactory.getLog(JeeDevViewResolverTestController.class);
    
    @RequestMapping(value = "/test1")
    public String test1(HttpServletRequest request, ModelMap map) {
        logger.info("使用JSP视图解析器");
        map.put("name", "hello world");
        return "jspTest.jsp";
    }
    
    @RequestMapping(value = "/test2")
    public String test2(HttpServletRequest request, ModelMap map) {
        logger.info("使用Freemarker视图解析器");
        map.put("name", "hello world");
        return "hello.ftl";
    }
    
    @RequestMapping(value = "/test3")
    public String test3(HttpServletRequest request, ModelMap map) {
        logger.info("使用Velocity视图解析器");
        map.put("name", "hello world");
        return "/html/demo.htm";
    }
}
复制代码

 

四.测试请求

我在web.xml里给DispatcherServlet添加了/view/*,所以,只要在请求前加上/view就可以了。

http://localhost:8080/view/demo/test1

http://localhost:8080/view/demo/test2

http://localhost:8080/view/demo/test3

皆验证通过。


第二种方式

说明一下目录结构
SpringMVC同时支持多视图(JSP,Velocity,Freemarker等)的一种思路实现_第1张图片 
Spring配置文件

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"
    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"
>
    
< context:component-scan
        
base-package ="com.spring.action"   />
    

    
< bean  class ="org.springframework.web.servlet.view.ResourceBundleViewResolver" >
        
< property  name ="basename"  value ="views" > property >
        

    
bean >
    
    

    
< bean  id ="jspViewResolver"  class ="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        
< property  name ="viewClass"  value ="org.springframework.web.servlet.view.JstlView" />
        
< property  name ="prefix"  value ="/" />
        
< property  name ="suffix"  value =".jsp" />
    
bean >         
    
    

    
< bean  id ="velocityViewResolver"  class ="org.springframework.web.servlet.view.velocity.VelocityViewResolver" >
        
< property  name ="cache"  value ="true" />
        
< property  name ="prefix"  value ="/" />
        
< property  name ="suffix"  value =".vm" />
    
bean >
    
    

    
< bean  id ="velocityConfig"  class ="org.springframework.web.servlet.view.velocity.VelocityConfigurer" >
        

        
< property  name ="configLocation"  value ="/WEB-INF/velocity.properties" />
        

        
< property  name ="resourceLoaderPath"  value ="/WEB-INF/velocity/" />
    
bean >
    
    

    
< bean  id ="freemarkerConfig"  class ="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
        

        
< property  name ="templateLoaderPath"  value ="/WEB-INF/freemarker/" />
    
bean >
    
    

    
< bean  id ="freeMarkerViewResolver"  class ="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" >
        
< property  name ="cache"  value ="true" />
        
< property  name ="prefix"  value ="/" />
        
< property  name ="suffix"  value =".ftl" />
    
bean >
beans >
views.properties
#welcome为modelAndView.setViewName( " welcome " ) ; 中的welcome   .(class)固定写法
welcome.(class) = org.springframework.web.servlet.view.velocity.VelocityView
#welcome.url 路径 welcome.vm模板名称
welcome.url
= welcome.vm

#freemarker为modelAndView.setViewName(
" freemarker " ) ; 中的freemarker   .(class)固定写法
freemarker.(class) = org.springframework.web.servlet.view.freemarker.FreeMarkerView
#freemarker.url 路径 freemarker.ftl模板名称
freemarker.url
= freemarker.ftl

第三种方式:自适应匹配,不存在则找下一种,使用orders





	
		
	

	
	

	
		
		
			
				
					
						text/plain;charset=UTF-8
						text/html;charset=UTF-8
					
				
			
			
				
					
						text/html;charset=UTF-8
						application/json;charset=UTF-8
					
				
			
		
	

	


	
	
		  
            /WEB-INF/ftl/  
          
		
		
			
				
			
		

		
			
				
				auto_detect
				
				UTF-8
				UTF-8
				zh_CN
				yyyy-MM-dd
				HH:mm:ss
				yyyy-MM-dd HH:mm:ss
				#.##
				
				true
				
				html_debug
				
			
		
	

	

	
	
		
		
		
		
		
		
		
	
	
	 
	
	
	
		
		
	
	
	
		
		
		
        
	
	 
	
	
		
	
	
	
		
		
		
		
	

 	
	
	
		
			
				outException
			
		
	
	







你可能感兴趣的:(SpringMvc-)