springboot模板引擎使用之freemarker

1、引入依赖

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

2、修改配置文件application.properties

# freemarker静态资源配置
spring.resources.static-locations=classpath:/static/
spring.mvc.static-path-pattern=/static/**
# 设定ftl文件路径
spring.freemarker.tempalte-loader-path=classpath:/templates
# 关闭缓存,及时刷新,上线生产环境需要修改为true
spring.freemarker.cache=false
#设定Template的编码
spring.freemarker.charset=UTF-8
#是否检查templates路径是否存在
spring.freemarker.check-template-location=true
#设定Content-Type
spring.freemarker.content-type=text/html
#设定所有request的属性在merge到模板的时候,是否要都添加到model中
spring.freemarker.expose-request-attributes=true
#设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-session-attributes=true
#指定RequestContext属性的名.
spring.freemarker.request-context-attribute=request
#设定模板的后缀
spring.freemarker.suffix=.ftl
#设定freemarker模板的前缀
#spring.freemarker.prefix

3、创建一个UserController.java

package com.xdw.springbootdemo5;

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

@Controller
public class UserController {

    /**
     * 采用model往request域中存值,存入2个普通的字符串
     * @param model
     * @return
     */
    @RequestMapping(value = "/userinfo1",method = RequestMethod.GET)
    public String userinfo1(Model model) {
        String username = "xiadewang";
        String password = "123456";
        model.addAttribute("username", username);
        model.addAttribute("password", password);
        return "userinfo1";
    }

}

4、创建一个ftl后缀的模板页面userinfo1.ftl

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <p>用户名:${username}</p>
    <p>密码:${password}</p>
</head>
<body>

</body>
</html>

5.运行项目访问

相关推荐