springboot整合freemarker以及auto_import、auto_include配置使用

1.application.properties配置:

# FREEMARKER (FreeMarkerAutoConfiguration) 
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=true
spring.freemarker.suffix=.html
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true
spring.freemarker.settings.date_format=yyyy-MM-dd
spring.freemarker.settings.time_format=HH:mm:ss
spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss
spring.freemarker.request-context-attribute=request
spring.freemarker.order=1
auto_import=ftl/spring.ftl as s
auto_include=

2.spring.ftl存放位置:

templates/ftl/spring.ftl
内容:<#assign base = request.contextPath />

3.freemarkerconfig配置:

@org.springframework.context.annotation.Configuration
public class FreemarkerConfig {
	
	private static Logger log = LoggerFactory.getLogger(FreemarkerConfig.class);
    
	@Bean
    public FreeMarkerConfigurer freeMarkerConfigurer(@Value("${auto_import}") String autoImport,@Value("${auto_include}") String autoInclude) throws Exception {
        FreeMarkerConfigurer config = new FreeMarkerConfigurer();
        writerProperties(config);
        Configuration configuration = null;
        try {
            configuration = config.createConfiguration();
        } catch (IOException e) {
            throw new ConfigException("freemarker配置bean,IO异常",e);
        } catch (TemplateException e) {
            throw new ConfigException("freemarker配置bean异常",e);
        }
        setAutoImport(autoImport,configuration);
        setAutoInclude(autoInclude,configuration);
        config.setConfiguration(configuration);
        return config;
    }
    @Autowired
    private FreeMarkerProperties properties;

    private void writerProperties(FreeMarkerConfigurer config) {
        config.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());
        config.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
        config.setDefaultEncoding(this.properties.getCharsetName());
        Properties settings = new Properties();
        settings.putAll(this.properties.getSettings());
        config.setFreemarkerSettings(settings);
    }
    
    private void setAutoImport(String autoImport,Configuration configuration) throws Exception {
        if("_".equals(autoImport.trim())) {
            return;
        }
        String[] imports = autoImport.split(";");
        Map<String,String> importMap = new HashMap<String,String>(imports.length);
        for (String s : imports) {
            String[] keyValue = s.split("as");
            if (keyValue.length != 2) {
                log.error("freemarker配置auto_import格式不正确 ");
                throw new ConfigException("freemarker配置auto_import格式不正确");
            }
            importMap.put(keyValue[1].trim(),keyValue[0].trim());
        }
        configuration.setAutoImports(importMap);
    }
    
    private void setAutoInclude(final String autoInclude,Configuration configuration) {
        if ("_".equals(autoInclude.trim())) {
            return;
        }
        String[] includes = autoInclude.split(";");
        for (String s : includes) {
            System.out.println(s);
        }
        List list = new ArrayList<String>(Arrays.asList(includes));
        configuration.setAutoIncludes(list);
    }
}

4.页面引用:

${s.base}或者使用${request.contextPath}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Freemarker是一种模板引擎,可以将数据和模板进行整合生成输出内容。SpringBoot提供了对Freemarker的支持,可以很方便地整合Freemarker。 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` 2. 配置文件 在application.properties文件中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.cache=false ``` - template-loader-path:模板文件的路径,这里设置为classpath:/templates/,表示在项目的classpath下的templates目录中查找模板文件。 - cache:是否开启模板缓存,这里设置为false,表示关闭缓存。 3. 创建模板文件 在classpath:/templates/目录下创建一个名为index.ftl的模板文件,内容如下: ```html <!DOCTYPE html> <html> <head> <title>SpringBoot整合Freemarker</title> </head> <body> <h1>${message}</h1> </body> </html> ``` 4. 创建控制器 创建一个名为IndexController的控制器,代码如下: ```java @Controller public class IndexController { @RequestMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, World!"); return "index"; } } ``` 该控制器中,使用@RequestMapping注解指定了请求路径为/,并将一个名为message的属性值设置为“Hello, World!”,然后返回了index作为视图名称。由于配置spring.freemarker.template-loader-path=classpath:/templates/,所以SpringBoot会在classpath:/templates/目录下查找名为index的模板文件,并将模板文件中的${message}替换为“Hello, World!”。 5. 运行程序 启动应用程序,访问http://localhost:8080/,可以看到页面中显示了“Hello, World!”的字样。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值