springboot: 集成freemark模板引擎

1.freemark简介(摘自:http://blog.csdn.net/liaomin416100569/article/details/78349072)

  在互联网软件内容网站中 一般首页的访问量大,为了提供首页的访问效率,一般 首页的内容以及其中的新闻等信息都可以实现html静态化 浏览器访问时

  设置浏览器的缓存策略和生成静态页面的周期一致 可以使访问效率大大提升 同时配合cdn处理图片 js css等资源 可以在首页访问时 理论完全脱离数据库  

  降低应用压力

  原理图:

   

2.代码

1).pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>lf</groupId>
    <artifactId>Springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!-- 继承 spring-boot-starter-paren -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
    </parent>
    <dependencies>
        <!-- SpringBoot 核心组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 引入freeMarker的依赖包. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
</project>

2).测试类:IndexController.java

package com.lf.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    
    @RequestMapping("index")
    public String index(ModelMap map){
        map.put("user", "大飞");
        map.put("sex", 1);
        List<Object> userList = new ArrayList<Object>();
        userList.add("小菜");
        userList.add("老秃子");
        userList.add("王麻子");
        map.put("userList", userList);
        return "index";
    }
    
}

  

3).FTL模板:index.ftl (springboot默认加载模板文件地址:/src/main/resources/templates)

<!DOCTYPE html >
<html>
<head lang="en">
<meta charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    用户:${user}
    性别:
    <#if sex==1><#elseif sex==2><#else>
        其他
    </#if>
    <br/><hr/>
    遍历集合:
    <#list userList as user>
        ${user}
    </#list>            
</body>
</html>

4).springboot启动类: ApplicationMain.java

package com.lf.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages="com.lf")
@EnableAutoConfiguration//此注释自动载入应用程序所需的所有Bean
public class ApplicationMain {
    
    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class, args);
    }
    
}

5).测试结果

原文地址:https://www.cnblogs.com/leifei/p/8342345.html