- <beans>
- <beanid="freeMarkerConfigurer"class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
- <propertyname="templateLoaderPath"value="/WEB-INF/config/template/"/>
- <propertyname="freemarkerSettings">
- <props>
- <propkey="template_update_delay">0</prop>
- <propkey="default_encoding">GBK</prop>
- <propkey="locale">zh_CN</prop>
- </props>
- </property>
- </bean>
- <beanid="freeMarkerConfiguration"class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
- <propertyname="templateLoaderPath"value="file:D:/Java/workspace/project/WebContent/WEB_INF/config/template"/>
- </bean>
- <beanid="templateService"class="com.ahtec.ssi.service.impl.TemplateServiceFreeMarkerImpl">
- <propertyname="freeMarkerConfigurer"ref="freeMarkerConfigurer"/>
- <propertyname="freeMarkerConfiguration"ref="freeMarkerConfiguration"/>
- </bean>
- </beans>
- //WEB
- Templatet=freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
- returnFreeMarkerTemplateUtils.processTemplateIntoString(t,model);
- //NONEWEB
- Templatet=freeMarkerConfiguration.getTemplate(templateName);
- returnFreeMarkerTemplateUtils.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<String, Object> 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; } }