springboot项目下使用Freemarker模板并调用远程模板

springboot项目环境下使用freemarker模板文件会打包到WEB-INF\classes 包下。修改静态资源或者模板文件时需要重新启动tomcat比较麻烦。
后调整项目环境实现使用远程模板 并兼容开发和线上模式,同时实现模板文件和静态文件的版本管理。

  1. 配置FreemarkerConfig 类

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.renmin.common.constants.SysConfig;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.TemplateDirectiveModel;

/**
 * 配置本地模板路径及远程模板路径
 */
@Configuration
public class FreemarkerConfig {
    
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
 
    @Autowired
    private WebApplicationContext applicationContext;

    @Autowired
    private SysConfig sysConfig;
    
    
    @PostConstruct
    public void freeMarkerConfigurer() throws IOException {
        freemarker.template.Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 注册所有自定义标签
        Map<String, TemplateDirectiveModel> tagsMap = applicationContext.getBeansOfType(TemplateDirectiveModel.class);
        Set<Map.Entry<String, TemplateDirectiveModel>> entries = tagsMap.entrySet();
        entries.forEach(entry -> configuration.setSharedVariable(entry.getKey(), entry.getValue()));
        // 远程模版加载
        // RemoteURLTemplateLoader remoteTemplateLoader = new RemoteURLTemplateLoader(remotePath);
        // 本地模版加载
        //ClassTemplateLoader classTemplateLoader = new ClassTemplateLoader(getClass(), "/templates/");
        String fullFreemarkerRemotePath = sysConfig.getFullFreemarkerRemotePath();
        File remoteFile = new File(fullFreemarkerRemotePath);
        //远程文件模板
        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(remoteFile);
        TemplateLoader[] templateLoaders = new TemplateLoader[] { fileTemplateLoader};
        MultiTemplateLoader templateLoader = new MultiTemplateLoader(templateLoaders);
        configuration.setTemplateLoader(templateLoader);
    }


}

@Configuration
public class SysConfig {
	
	/** 项目挂载路径 此路径包含 文件上传、模板、IP解析 */
    @Value("${config.project_mount_path}")
    public String projectMountPath;
    /** freemarker 模板相对路径*/
	@Value("${config.freemarker_remote_path}")
    private String freemarkerRemotePath;
	/** 项目运行环境 本地 或 线上*/
    @Value("${config.environment_type}")
    private String environmentType;
    /** ip解析dat文件相对路径*/
	@Value("${config.ipseek_path}")
    public String ipseekPath;
    /** 上传路径 */
    @Value("${config.profile}")
    private String profile;

	/**
     * 获取项目全路径
     * 
     * @return
     */
    public String getFullProjectMountPath() {
        if ("dev".equals(getEnvironmentType())) {
            // 开发环境
            String projectDir = System.getProperty("user.dir");
            return projectDir + getProjectMountPath();
        } else {
            // 生产环境
            return getProjectMountPath();
        }

    }
    
	/**
     * 获取QQWry.Dat文件真实物理地址
     * 
     * @return
     */
	public String getFullIpseekPath() {
        return getFullProjectMountPath() + getIpseekPath();
    }
    
	/**
     * 获取模板全路径
     * 
     * @return
     */
    public String getFullFreemarkerRemotePath() {
        return getFullProjectMountPath() + getFreemarkerRemotePath();
    }
    
	/**
	 * 文件上传全路径
	 * 
	 * @return
	 */
	public String getFullUploadPath() {
		return getFullProjectMountPath() + getProfile();
	}
	
	public String getProjectMountPath() {
        return projectMountPath;
    }

    public void setProjectMountPath(String projectMountPath) {
        this.projectMountPath = projectMountPath;
    }

    public String getFreemarkerRemotePath() {
        return freemarkerRemotePath;
    }

    public void setFreemarkerRemotePath(String freemarkerRemotePath) {
        this.freemarkerRemotePath = freemarkerRemotePath;
    }

    public String getEnvironmentType() {
        return environmentType;
    }

    public void setEnvironmentType(String environmentType) {
        this.environmentType = environmentType;
    }
	
	public String getIpseekPath() {
		return ipseekPath;
	}

	public void setIpseekPath(String ipseekPath) {
		this.ipseekPath = ipseekPath;
	}
	
	public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }
}


  1. 配置拦截 InterceptorConfig 类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.renmin.common.constants.Constants;
import com.renmin.common.constants.SysConfig;
import com.renmin.core.interceptor.AdminInterceptor;
import com.renmin.core.interceptor.MemberInterceptor;

/**
 * 拦截器配置
 * 
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private SysConfig sysConfig;

    /**
     * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index");
        registry.addViewController("/admin").setViewName("forward:/admin/index");
        // tomcat 文档漏洞拦截
        registry.addViewController("/examples/**").setViewName("forward:/admin/index");
        registry.addViewController("/docs/**").setViewName("forward:/admin/index");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 静态资源文件 */
        registry.addResourceHandler("/static/**")
            .addResourceLocations("file:" + sysConfig.getFullProjectMountPath() + "/static/");
        /** 本地文件上传路径 */
        registry.addResourceHandler("/profile/**")
            .addResourceLocations("file:" + sysConfig.getFullUploadPath() + "/");

    }

    @Bean
    public AdminInterceptor getAdminInterceptor() {
        return new AdminInterceptor();
    }

    @Bean
    public MemberInterceptor getMemberInterceptor() {
        return new MemberInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(getAdminInterceptor());
        registration.excludePathPatterns("/admin/login");
        registration.excludePathPatterns("/admin/logout");
        registration.excludePathPatterns("/static/**");
        registration.addPathPatterns("/admin/**");
        // tomcat 文档漏洞拦截
        registration.addPathPatterns("/examples/**");
        registration.addPathPatterns("/docs/**");

        InterceptorRegistration memberRegistration = registry.addInterceptor(getMemberInterceptor());
        memberRegistration.addPathPatterns("/member/**");
        memberRegistration.addPathPatterns("/api/**");
        memberRegistration.excludePathPatterns("/static/**");
    }

}

yml文件配置

开发环境
#自定义属性配置
config:
  #项目挂载路径
  project_mount_path : /mount
  #环境区分 dev online
  environment_type : dev
  # 文件模板
  freemarker_remote_path : /freemarker_tpl
  # 文件路径 示例
  profile: /upload_path

线上环境
#自定义属性配置
config:
  #项目挂载路径
  project_mount_path : /app/project/mount
  #环境区分 dev online
  environment_type : online
  # 文件模板
  freemarker_remote_path : /freemarker_tpl

外部资源文件目录
在这里插入图片描述

您好!对于Spring Boot使用Freemarker模板生成Word文档并加密的例子,可以按照以下步骤进行操作: 1. 首先,您需要在pom.xml文件中添加Freemarker和Apache POI的依赖项。在 `<dependencies>` 标签内添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Freemarker模板文件,例如 `template.ftl`,并在其中编写Word文档的内容,可以使用Freemarker语法进行动态内容替换。 3. 创建一个Controller类,并添加以下代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFEncryptor; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @Controller public class WordController { @Autowired private Configuration freemarkerConfiguration; @GetMapping("/generate-word") public void generateWord(HttpServletResponse response) throws Exception { // 加载Freemarker模板 Template template = freemarkerConfiguration.getTemplate("template.ftl"); // 创建Word文档对象 XWPFDocument document = new XWPFDocument(); // 创建段落对象 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 填充模板内容 Map<String, Object> data = new HashMap<>(); // 添加模板中需要的数据,可以根据实际需求自行修改 // 渲染模板 run.setText(templateToString(template, data)); // 加密Word文档 XWPFEncryptor encryptor = new XWPFEncryptor(document); encryptor.encrypt("password"); // 替换为您自己的密码 // 设置响应头 response.setHeader("Content-disposition", "attachment; filename=encrypted_word.docx"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // 导出Word文档 OutputStream outputStream = response.getOutputStream(); document.write(outputStream); outputStream.close(); } private String templateToString(Template template, Map<String, Object> data) throws Exception { StringWriter stringWriter = new StringWriter(); template.process(data, stringWriter); return stringWriter.toString(); } } ``` 4. 在Spring Boot的配置文件(例如 `application.properties`)中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ ``` 5. 运行Spring Boot应用程序,并访问 `/generate-word` 路径,即可生成并下载加密的Word文档。 请注意,上述代码仅为示例,您可以根据实际需求进行修改和扩展。同时,为了确保文档的安全性,请根据您的需求修改加密密码和文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值