springboot 集成 freemarker

前面我们已经实现了thymeleaf模板,其实freemarker和thymeleaf差不多,都可以取代JSP页面,实现步骤也差不多,我们来简单实现一下

引入pom.xml依赖如下

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

创建Controller测试类

/**
 * @author pillarzhang
 * @date 2019-06-03
 */
@Controller
class FreemarkerController {
    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("name","hello pillar");
        return "index";
    }
}

application.properties配置文件你可以选择不配置默认,也可以进行手动配置

选择默认时配置路径一定要写对,src/main/resources  static(js,css等静态文件),templates(页面路径)注意是ftl后缀

如果要自定义的话,可以在application.properties中设置如下等配置信息

spring.freemarker.charset=UTF-8
spring.freemarker.suffix=.ftl
spring.freemarker.content-type=text/html; charset=utf-8
spring.freemarker.template-loader-path=classpath:/templates
spring.mvc.static-path-pattern=/static/**

Index.ftl文件如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>FreeMarker</title>
</head>
<body>
<h1>hello world</h1>
<h1 style="color: red">${name}</h1>
</body>
</html>

启动项目,输入地址http://localhost:8080/index显示如下则成功

详细配置文件

# 是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-request-override=false
# 是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。
spring.freemarker.allow-session-override=false
# 是否启用模板缓存。
spring.freemarker.cache=false
# 模板编码。
spring.freemarker.charset=UTF-8
# 是否检查模板位置是否存在。
spring.freemarker.check-template-location=true
# Content-Type value.
spring.freemarker.content-type=text/html
# 是否启用freemarker
spring.freemarker.enabled=true
# 设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-request-attributes=false
# 是否在merge模板的时候,将HttpSession属性都添加到model中
spring.freemarker.expose-session-attributes=false
# 设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.freemarker.expose-spring-macro-helpers=true
# 是否优先从文件系统加载template,以支持热加载,默认为true
spring.freemarker.prefer-file-system-access=true
# 设定模板的后缀.
spring.freemarker.suffix=.ftl
# 设定模板的加载路径,多个以逗号分隔,默认:
spring.freemarker.template-loader-path=classpath:/templates/
# 设定FreeMarker keys.
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true

通过freemarker生成静态html

首先需要编写一个可以在普通类中获取到springbean的工具类SpringContextHolder

@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext appContext = null;

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return appContext.getBean(name);

    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return appContext.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return appContext.getBean(name, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (appContext == null) {
            appContext = applicationContext;
        }
    }
}

然后编写一个生成静态html文件的工具类FreemarkerUtil

public class FreemarkerUtil {

    public static String parseTpl(String viewName, Map<String, Object> params) {
        Configuration cfg = SpringContextHolder.getBean(Configuration.class);
        String html = null;
        Template t = null;
        try {
            t = cfg.getTemplate(viewName + ".ftl");
            html = FreeMarkerTemplateUtils.processTemplateIntoString(t, params);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return html;
    }
}

为了方便查看, 添加一个mapping

@RequestMapping("/createHtml")
@ResponseBody
public String createHtml(Model model){
    Map map = new LinkedHashMap<>();
    for (int i = 0; i < 5; i++) {
        map.put("key" + i, "value" + i);
    }
    model.addAttribute("list", Arrays.asList("string1", "string2", "string3", "string4", "string5", "string6"));
    model.addAttribute("map", map);
    model.addAttribute("name", "   htTps://wWw.zHyD.mE   ");
    model.addAttribute("htmlText", "<span style=\"color: red;font-size: 16px;\">html内容</span>");
    model.addAttribute("num", 123.012);
    model.addAttribute("null", null);
    model.addAttribute("dateObj", new Date());
    model.addAttribute("bol", true);
    return FreemarkerUtil.parseTpl("index", model.asMap());
}

ok,访问/createHtml

到此为止,本篇已详细介绍了freemarker的使用方法。

原文地址:https://www.cnblogs.com/wpcnblog/p/11857165.html

时间: 2024-07-29 13:51:24

springboot 集成 freemarker的相关文章

spring-boot集成Freemarker开发

1.该demo功能http://localhost/system/login展示后台发布新闻列表http://localhost/前端Freemark模板展示中间用到了Mysql, Mybatis, druid;可以参考spring-boot相关的demo 2.Pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freem

第三章 SpringBoot 集成框架(二)

1.SpringBoot 默认能直接访问的静态资源目录: /static    public  /resources  /META-INF/resources 2.SpringBoot 集成 JSP :需要添加 JSP 的依赖 ,JSP 页面使用 JSTL 标签 . 3.SpringBoot 框架集成 JSP 时,打包的格式是war          打包:右键项目 --> Run as --> Maven build...    pom.xml中的打包方式:<packaging>

SpringBoot集成MyBatis的分页插件PageHelper

俗话说:好??不吃回头草,但是在这里我建议不管你是好马还是不好马,都来吃吃,带你复习一下分页插件PageHelper. 昨天给各位总结了本人学习springboot整合mybatis第一阶段的一些学习心得和源码,主要就算是敲了一下SpringBoot的门儿,希望能给各位的入门带给一点儿捷径,今天给各位温习一下MyBatis的分页插件PageHelper和SpringBoot的集成,它的使用也非常简单,开发更为高效.因为PageHelper插件是属于MyBatis框架的,所以相信很多哥们儿都已经用

springboot集成swagger2构建RESTful API文档

在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可以在访问接口上,直接添加注释 先介绍一下开发环境: jdk版本是1.8 springboot的版本是1.4.1 开发工具为 intellij idea 我们先引入swagger2的jar包,pom文件引入依赖如下: <dependency> <groupId>io.springfox&

spring-boot集成Springfox-Swagger2

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documenta

【spring-boot】spring-boot集成ehcache实现缓存机制

EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

SpringBoot集成MyBatis的分页插件PageHelper(回头草)

俗话说:好??不吃回头草,但是在这里我建议不管你是好马还是不好马,都来吃吃,带你复习一下分页插件PageHelper. 昨天给各位总结了本人学习springboot整合mybatis第一阶段的一些学习心得和源码,主要就算是敲了一下SpringBoot的门儿,希望能给各位的入门带给一点儿捷径,今天给各位温习一下MyBatis的分页插件PageHelper和SpringBoot的集成,它的使用也非常简单,开发更为高效.因为PageHelper插件是属于MyBatis框架的,所以相信很多哥们儿都已经用

springboot集成redis详解

欢迎扫码加入Java高知群交流 springboot集成redis非常简单 1.引入maven依赖redis包 <!-- springboot整合 redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> 2.appli

springboot集成jsp

springboot集成jsp需要的依赖如下: <!--配置servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!--配置jsp jstl的支持--> <dependency> <groupId>javax.se