FreeMarker自定義指令自動加載

wdl 8年前發布 | 1K 次閱讀 Java FreeMarker

FreeMarker自定義指令目前大多項目都需要在XML中配置,比如
<property name="freemarkerVariables">
        <map>
            <entry key="xml_escape" value-ref="fmXmlEscape" />
        </map>
 </property>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
使用自動加載只需要制定好一定的規則,就可以在每次工程啟動時自動加載所有自定義指令
</div>

 

FreeMarker自定義指令自動加載    

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) {
        }
    }
}
 本文由用戶 wdl 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!