6、SpringBoot整合Freemarker

步骤

  1. 创建项目
  2. 修改POM文件,添加Freemarker启动器
  3. 创建Controller
  4. 创建Users实体
  5. 添加Freemarker文件配置
  6. 创建视图

Freemarker也是视图层技术,与Thymeleaf相似,他们都被称为模板视图

添加Freemarker依赖

<!--Freemarker启动器依赖-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

创建User实体类

public class Users {
    private String username;
    private String usersex;
    private String userage;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsersex() {
        return usersex;
    }

    public void setUsersex(String usersex) {
        this.usersex = usersex;
    }

    public String getUserage() {
        return userage;
    }

    public void setUserage(String userage) {
        this.userage = userage;
    }
}

创建Controller

/**
* UserController
*/
@Controller
public class UsersController {
    /**
     * 处理请求,返回数据
     */
    @GetMapping("/showUsers")
    public String showUsers(Model model){
        List<Users> list = new ArrayList<>();
        list.add(new Users("admin","F","32"));
        list.add(new Users("lili","m","23"));
        model.addAttribute("list",list);
        return "usersList";
    }
}

添加配置

spring.freemarker.suffix=.ftl

创建视图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1" align="center" width="50%">
        <tr>
            <th>Name</th>
            <th>Sex</th>
            <th>Age</th>
        </tr>
        <#list list as user>
            <tr>
                <td>${user.username}</td>
                <td>${user.usersex}</td>
                <td>${user.userage}</td>
            </tr>
        </#list>
    </table>
</body>
</html>
posted @ 2020-08-28 12:50  lawrence林  阅读(137)  评论(0编辑  收藏  举报