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

在Spring Boot项目中,使用Freemarker模板文件打包到特定包下,修改静态资源或模板文件需重启Tomcat。通过调整项目环境,实现使用远程模板,兼容开发和线上模式,还实现了模板和静态文件的版本管理,涉及配置相关类、yml文件及外部资源目录。

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应用中,接口调用时通常涉及前后端分离的场景,尤其是RESTful API的设计。为了避免页面跳转,可以采用以下几种方法: 1. **使用`@RestController`注解** 在Controller类上使用`@RestController`替代`@Controller`和模板引擎相关的配置。`@RestController`是`@Controller`与`@ResponseBody`的组合注解,它会将返回值直接序列化为JSON或XML格式,返回给客户端,而不是触发页面跳转。 ```java @RestController public class MyController { @GetMapping("/api/data") public String getData() { return "This is JSON data"; } } ``` 2. **避免引入模板引擎依赖** 如果项目不需要渲染HTML页面,则可以在`pom.xml`(Maven)或`build.gradle`(Gradle)中移除Thymeleaf、Freemarker模板引擎的依赖。这样,Spring Boot不会自动配置视图解析器,从而避免页面跳转。 3. **禁用视图解析器自动配置** 在`application.properties`或`application.yml`中禁用默认的视图解析器,防止其尝试解析跳转到HTML页面。 ```properties spring.mvc.view.prefix= spring.mvc.view.suffix= ``` 或者在配置类中显式地移除视图解析器: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.disableContentNegotiation(); } } ``` 4. **使用`ResponseEntity`返回数据** 在接口方法中使用`ResponseEntity`包装响应数据,确保返回内容为纯数据格式而非视图名称。 ```java @GetMapping("/api/data") public ResponseEntity<String> getData() { return ResponseEntity.ok("This is JSON data"); } ``` 5. **确保没有返回视图名称字符串** 避免在接口方法中返回字符串类型的视图名称,如`"home"`或`"index"`,因为这可能被误认为是需要跳转的页面路径。 6. **通过Feign Client调用外部接口** 如果是跨系统调用,可以通过Feign Client实现远程服务调用,而不会涉及到页面跳转的问题。启动类上需添加`@EnableFeignClients`以启用Feign客户端功能[^4]。 ```java @FeignClient(name = "service-provider") public interface ServiceClient { @GetMapping("/data") String getData(); } ``` 7. **使用Zuul进行路由转发(适用于网关层)** 如果应用作为网关,可使用Zuul进行路由转发,避免直接处理页面跳转逻辑。启动类上需添加`@SpringCloudApplication`和相关注解[^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值