zoukankan      html  css  js  c++  java
  • Spring Boot入门系列五(FreeMarker模板的使用)

    FreeMarker模板的使用

      FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
      FreeMarker是免费的,基于Apache许可证2.0 版本发布。其模板编写为 FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据。

    使用方法;

    一、在pom.xml中引入依赖

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

    二、在application.properties中配置FreeMarker

    ############################################################
    #
    # freemarker
    #
    ############################################################
    spring.freemarker.template-loader-path=classpath:/templates
    spring.freemarker.cache=false
    spring.freemarker.charset=UTF-8
    spring.freemarker.check-template-location=true
    spring.freemarker.content-type=text/html
    spring.freemarker.expose-request-attributes=true
    spring.freemarker.expose-session-attributes=true
    spring.freemarker.request-context-attribute=request
    spring.freemarker.suffix=.ftl
    

    三、创建index.ftl文件,用于在浏览器端展示数据

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8"/>
        <title></title>
    </head>
    <body>
    FreeMarker模板引擎
    <h1>${resource.name}</h1>
    <h1>${resource.webSite}</h1>
    <h1>${resource.language}</h1>
    </body>
    </html>
    

      

    四、创建Controller,用于向前端页面返回数据

      

    /**
     * @author oyc
     * @Title:
     * @Description:
     * @date 2018/6/1323:15
     */
    
    @Controller
    @RequestMapping("ftl")
    public class FreemarkerController {
    
        @Autowired
        private Resource resource;
    
        @RequestMapping("/index")
        public String index(ModelMap map) {
            map.addAttribute("resource", resource);
            return "freemarker/index";
        }
    }
    

      

    六、在浏览器访问相应的地址,即可展现我们猜想到的界面:

      

    --------------少年不努力,长大搞程序。欢迎关注,如有错误,恳请指正。
  • 相关阅读:
    twitter分享问题(三)——Required oauth_verifier parameter not provided
    旋转数组的最小数字
    关系型数据库基础之:简单的数据查询
    twitter分享问题(一)——MISSING_ARG_APIKEY
    extern "C"的理解
    从一个链接错误探究GCC的链接库顺序
    GAE 博客——B3log Solo 0.4.0 正式版发布了!
    不使用资源文件动态创建对话框的做法
    GAE 博客——B3log Solo 0.4.0 正式版发布了!
    CodeBlocks启动多个进程实例的做法
  • 原文地址:https://www.cnblogs.com/oycyqr/p/9180824.html
Copyright © 2011-2022 走看看