springboot支持freemarker 06

freemarker是一模板技术,用来代替较重的jsp,本文讲述springboot如何整合freemarker。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

  • 完成springboot创建web项目 https://www.jianshu.com/p/de979f53ad80
    注意:笔者创建项目的时候约束的包前缀是net.wanho.springboot.springbootfreemarkerdemo,读者可以自行创建包名,只是要注意本文中的代码也要修改包名

3、修改pom.xml

在dependencies标签中加入以下依赖:

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

修改application.properties,加入以下内容:

spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates

4、在net.wanho.springboot.springbootfreemarkerdemo包下面创建controller、entity子包

在entity下创建User.java

package net.wanho.springboot.springbootfreemarkerdemo.entity;

public class User
{
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在controller下面创建UserController.java

package net.wanho.springboot.springbootfreemarkerdemo.controller;

import net.wanho.springboot.springbootfreemarkerdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
@RequestMapping(value = "/user")
public class IndexController {


    @RequestMapping(value = "/show")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("index");
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "zhangli"));
        userList.add(new User(2, "ali"));
        userList.add(new User(3, "xiaoli"));
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    @RequestMapping("/gen1")
    @ResponseBody
    public String genFreemarkerFile()throws Exception
    {

        // 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 第二步:设置模板文件所在的路径。
        Resource resource = new ClassPathResource("templates/");
        configuration.setDirectoryForTemplateLoading(resource.getFile());
        // 第三步:设置模板文件使用的字符集。一般就是utf-8.
        configuration.setDefaultEncoding("utf-8");
        // 第四步:加载一个模板,创建一个模板对象。
        /**
        hello.ftl的内容为
        ${hello!}${name!}
       **/
        Template template = configuration.getTemplate("hello.ftl");
        // 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
        Map dataModel = new HashMap<>();
        //向数据集中添加数据
        dataModel.put("hello", "this is my first freemarker test.");
        dataModel.put("name", "zhangli");
        // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。请确保D盘存在
        Writer out = new FileWriter(new File("D://hello.html"));
        // 第七步:调用模板对象的process方法输出文件。
        template.process(dataModel, out);
        // 第八步:关闭流。
        out.close();
        return "ok";
    }
}

    @RequestMapping("/gen2")
    @ResponseBody
    public String genFreemarkerFile()throws Exception
    {

        // 第一步:设置模板,此时的模板就是一个字符串,而不再是ftl文件
         String templateString = "欢迎${username}登录!"
        // 第二步:生成templdate
    Template template  = new Template("template", new StringReader(templateString), new Configuration(Configuration.VERSION_2_3_23));    
        // 第三步:设置数据
        Map dataModel = new HashMap<>();
        //向数据集中添加数据
        dataModel.put("username", "zhangli");
        // 第四步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。请确保D盘存在。
        Writer out = new FileWriter(new File("D://hello.html"));
        // 第五步:调用模板对象的process方法输出文件。
        template.process(dataModel, out);
        // 第六步:关闭流。
        out.close();
        return "ok";
    }

5、在resources/templates下创建index.ftl【注意,依赖的css,js需要读者自行导入】

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
    <link rel="stylesheet" href="/css/bootstrap.min.3.3.5.css"/>
    <script src="/js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="/js/bootstrap.js" type="text/javascript"></script>
</head>
<body>
    <table class="table">
        <caption>用户基本信息</caption>
        <thead>
        <tr>
            <th>id</th>
            <th>姓名</th>
        </tr>
        </thead>
           <#list userList as user>
            <tr>
                <td>${user.id!}</td>
                <td>${user.name!}</td>
            </tr>
           </#list>
    </table>
</body>
</html>

6、启动测试

在浏览器中输入http://localhost:8080/user/show,查看效果,具体情况如下:

 
16204070-ee25be79311fa3b0.gif
测试


至此,我们完成了springboot支持freemarker,并完成了测试。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值