两种Freemarker模板路径设置方法

<beans>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/config/template/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0prop>
<prop key="default_encoding">GBKprop>
<prop key="locale">zh_CNprop>
props>
property>
bean>
<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="file:D:/Java/workspace/project/WebContent/WEB_INF/config/template" />
bean>
<bean id="templateService" class="com.ahtec.ssi.service.impl.TemplateServiceFreeMarkerImpl">
<property name="freeMarkerConfigurer" ref="freeMarkerConfigurer" />
<property name="freeMarkerConfiguration" ref="freeMarkerConfiguration" />
bean>
beans>

 

//WEB
Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
//NONE WEB
Template t = freeMarkerConfiguration.getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);

在 web 中,可以方便地定位到WEB_INF目录,但在非web中就不那么容易了。综合考虑,将ftl模板放在classpath目录挺好的。用classpath:来定位模板位置。

补一段代码:

@Component public class TemplateServiceFreeMarkerImpl implements TemplateService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Autowired private Configuration freeMarkerConfiguration; public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) { this.freeMarkerConfigurer = freeMarkerConfigurer; } public void setFreeMarkerConfiguration(Configuration freeMarkerConfiguration) { this.freeMarkerConfiguration = freeMarkerConfiguration; } public String getContent(String templateName, Map model) { try { Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(t, model); } catch (Exception ex) { ex.printStackTrace(); logger.equals(ex.getMessage()); try { Template t = freeMarkerConfiguration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(t, model); } catch (Exception e) { e.printStackTrace(); logger.equals(e.getMessage()); } } return null; } }

 

Freemarker多路径配置方法:

<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths">
<list>
<value>/Freemarker/value>
<value>/Freemarker/error/value>
list>
property>
bean>

 

 

 

你可能感兴趣的:(两种Freemarker模板路径设置方法)