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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值