现在的位置: 首页 > 综合 > 正文

FreeMarker与SpringMVC整合实例代码教程

2017年11月24日 ⁄ 综合 ⁄ 共 4817字 ⁄ 字号 评论关闭

增加视图XML配置/testMvc/src/main/resources/conf/springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd


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-3.0.xsd


http://www.springframework.org/schema/tx

		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
	default-autowire="byName">

	<context:component-scan base-package="com.tangq.test" />
	
	<mvc:annotation-driven/>  
	
	<bean id="freemarkerConfiguration"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="location" value="classpath:/freemarker.properties" />
	</bean>

	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="freemarkerSettings" ref="freemarkerConfiguration"></property>
		<property name="templateLoaderPath" value="template/pages/" />
		<property name="defaultEncoding" value="utf-8" />
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="cache" value="true" />
		<property name="prefix" value="" />
		<property name="suffix" value=".ftl" />
		<property name="contentType" value="text/html;charset=UTF-8" />
	</bean>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="template/pages/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>
	
</beans>

上面配置中先查找 FreeMarker模板ftl后缀文件,如果找不到,才会去找后面的jsp文件

如果更换后面两个bean的顺序,则会先去找jsp文件,找不到时才去查找ftl模板


需要引入包freemarker-2.3.18.jar

如果是用maven方式构建项目,在pom文件中增加依赖包申明

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.18</version>
</dependency>


另附手动读取FreeMarker配置文件freemarker.properties,进行模板输出配置。获取模板输出字符串辅助类,

有疑问的可以密我,代码如下

/**
 * <模板IO操作管理类>
 */
public class TemplateIOManager {
    
    private static final Logger logger = LoggerFactory.getLogger(TemplateIOManager.class);
    
    private static FreeMarkerConfigurer freeMarkerConfigurer;
    
    private static Configuration DEFAULT_CONFIG;
    
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        TemplateIOManager.freeMarkerConfigurer = freeMarkerConfigurer;
    }
    
    /**
     * <获取模板输出字符串>
     * @param ftlName
     * @param data
     * @return
     */
    public static String parse(String ftlName, Map<String, Object> data) {
        String result = null;
        Template t;
        try {
            if (freeMarkerConfigurer != null) {
                t = freeMarkerConfigurer.getConfiguration().getTemplate(ftlName);
                result = FreeMarkerTemplateUtils.processTemplateIntoString(t, data);
            }
            else {
                t = getDefaultConfig().getTemplate(ftlName);
                result = FreeMarkerTemplateUtils.processTemplateIntoString(t, data);
            }
        }
        catch (IOException e) {
            logger.error(" ftl output IOException ,while ftlName=" + ftlName, e);
        }
        catch (TemplateException e) {
            logger.error(" ftl output TemplateException ,while ftlName=" + ftlName, e);
        }
        return result;
    }
    
    private static Configuration getDefaultConfig() {
        if (DEFAULT_CONFIG == null)
            DEFAULT_CONFIG = createDefaultCfg();
        return DEFAULT_CONFIG;
    }
    
    /**
     * <获取模板配置项>
     * @param loaderPath
     * @return
     */
    private static Configuration createDefaultCfg() {
        Configuration cfg = new Configuration();
        
        // 设置模板文件所在的目录
        try {
            cfg.setDirectoryForTemplateLoading(new File(getTemplateLoaderPath()));
        }
        catch (IOException e) {
            logger.error("设置模板加载目录失败", e);
        }
        
        Properties p = new Properties();  
        try {
            p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));
            cfg.setSettings(p);
        }
        catch (IOException e) {
            logger.error("获取freemarker.properties配置项io流异常", e);
        }
        catch (TemplateException e) {
            logger.error("配置模板发生异常", e);
        }
        
        return cfg;
    }
    
    /**
     * <获取模板加载目录>
     * @return
     */
    private static String getTemplateLoaderPath() {
        String path = TemplateIOManager.class.getResource("/").getFile();
        String fileSeparator = System.getProperty("file.separator");
        path = path.replace(fileSeparator, "/");
        path = path.substring(0, path.indexOf("WEB-INF")) + "template/pages/";
        return path;
    }
    
}

上面类的freeMarkerConfigurer属性由spring注入,在springMVC-servlet.xml中增加bean配置

<bean class="com.gvtv.app.epg.service.xml.TemplateIOManager">
     <property name="freeMarkerConfigurer" ref="freemarkerConfig" />
</bean>

还有freemarker.properties配置如下

datetime_format=yyyy-MM-dd HH:mm:ss
date_format=yyyy-MM-dd
time_format=HH:mm:ss
boolean_format=true,false
whitespace_stripping=true
default_encoding=UTF-8
tag_syntax=auto_detect
url_escaping_charset=UTF-8
classic_compatible=true
number_format=#

抱歉!评论已关闭.