原freemarker配置的ftl读取路径是默认在classes下,
增加userConfiguration配置使其可以在web路径下读取ftl
struts.properties文件中
struts.freemarker.manager.classname= net.esj.basic.plugins.freemarker.SpringConfigToFreemarkerManager
增加userConfiguration配置使其可以在web路径下读取ftl
- package net.esj.basic.plugins.freemarker;
- import java.io.File;
- import java.io.IOException;
- import javax.servlet.ServletContext;
- import net.esj.basic.utils.ApplicationBeanContext;
- import org.apache.struts2.views.freemarker.FreemarkerManager;
- import org.springframework.context.annotation.Scope;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
- import freemarker.template.Configuration;
- import freemarker.template.TemplateException;
- /**
- * 将struts的freemarkerManager配置放置在spring容器中维护
- * @author Administrator
- *
- */
- @Component("springConfigToFreemarkerManager")
- @Scope("prototype")
- public class SpringConfigToFreemarkerManager extends FreemarkerManager {
- private static final String SPRING_FREEMARKER_BEAN = "freemarkerConfig";
- private Configuration userConfiguration;
- @Override
- protected Configuration createConfiguration(ServletContext servletContext)
- throws TemplateException {
- FreeMarkerConfigurer fmconfig = (FreeMarkerConfigurer) ApplicationBeanContext.getBean(SPRING_FREEMARKER_BEAN);
- try {
- Configuration configuration =fmconfig.createConfiguration();
- configuration.setWhitespaceStripping(true);
- return configuration;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return super.createConfiguration(servletContext);
- }
- protected Configuration createUserConfiguration(ServletContext servletContext) throws TemplateException{
- userConfiguration =createConfiguration(servletContext);
- String realpath = servletContext.getRealPath("/");
- try {
- userConfiguration.setDirectoryForTemplateLoading(new File(realpath));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return userConfiguration;
- }
- public Configuration getUserConfiguration(ServletContext servletContext) {
- if(userConfiguration==null){
- try {
- createUserConfiguration(servletContext);
- } catch (TemplateException e) {
- e.printStackTrace();
- }
- }
- return userConfiguration;
- }
- }
struts.properties文件中
struts.freemarker.manager.classname= net.esj.basic.plugins.freemarker.SpringConfigToFreemarkerManager
本文详细介绍了如何通过Spring配置实现Freemarker模板在Web路径下的读取,不再局限于默认的classes目录,提供了一种更灵活的模板管理方式。

201

被折叠的 条评论
为什么被折叠?



