FreeMarker自定义指令目前大多项目都需要在XML中配置,比如

<property name="freemarkerVariables">

        <map>

            <entry key="xml_escape" value-ref="fmXmlEscape" />

        </map>

 </property>

<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>

使用自动加载只需要制定好一定的规则,就可以在每次工程启动时自动加载所有自定义指令。

在与Spring集成使用时,完全可以借助Spring的按基类注入特性,将所有实现自定义指令的bean注入到FreeMarker的ShareVariables中,这样节省部分开发人员的工作,也防止指令过多后管理不便,以下是从PublicCMS中截取的代码实现

package com.sanluan.common.handler;

 

import static org.apache.commons.logging.LogFactory.getLog;

 

import java.util.HashMap;

import java.util.Map;

import java.util.Map.Entry;

 

import org.apache.commons.logging.Log;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

 

import freemarker.template.SimpleHash;

import freemarker.template.TemplateDirectiveModel;

import freemarker.template.TemplateModelException;

 

@Component

public class FreeMarkerExtendHandler implements ApplicationContextAware {

    private final Log log = getLog(getClass());

    @Autowired

    private Map<String, TemplateDirectiveModel> directiveMap;

    @Autowired

    private FreeMarkerConfigurer freeMarkerConfigurer;

 

    @Override

    public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException {

        log.info("Freemarker directives and methods Handler started");

        Map<String, Object> freemarkerVariables = new HashMap<String, Object>();

 

        StringBuffer directives = new StringBuffer();

        for (Entry<String, TemplateDirectiveModel> entry : directiveMap.entrySet()) {

            freemarkerVariables.put(entry.getKey(), entry.getValue());

            if (0 != directives.length())

                directives.append(",");

            directives.append(entry.getKey());

        }

 

        try {

            freeMarkerConfigurer.getConfiguration().setAllSharedVariables(

                    new SimpleHash(freemarkerVariables, freeMarkerConfigurer.getConfiguration().getObjectWrapper()));

            log.info((directiveMap.size()) + " directives created:[" + directives.toString() + "];");

        } catch (TemplateModelException e) {

        }

    }

}


标签:PublicCMS

匠人匠心科技是专业从事天津网站建设、天津网站制作、软件开发、移动建站、商城、微信端、app开发项目
软件事业部:天津市大学软件学院D-510(天津工业大学院内)
网站事业部: 天津市河北区新大路通广科技园3-225
咨询热线:138-2142-0129 136-2215-0903
天津网站建设_天津建站

扫码添加微信