Spring Boot整合FreeMarker

本文讲解如何在Spring Boot整合FreeMarker。

1 创建项目,导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<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>com.yiidian</groupId>
    <artifactId>ch03_05_springboot_freemarker</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! -->
    <!-- 父工程的作用:锁定起步的依赖的版本号,并没有真正到依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
    </parent>

    <dependencies>
        <!--web起步依赖-->
        <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>

这里记得要到FreeMarker的依赖,否则无法运行!

2 编写Controller

package com.yiidian.controller;
import java.util.ArrayList;
import java.util.List;

import com.yiidian.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器
 * 一点教程网 - www.yiidian.com
 */
@Controller
public class UserController {

	/**
	 * 用户列表展示
	 */
	@RequestMapping("/list")
	public String list(Model model){
		//模拟用户数据
		List<User> list = new ArrayList<User>();
		list.add(new User(1,"小张",18));
		list.add(new User(2,"小李",20));
		list.add(new User(3,"小陈",22));

		//把数据存入model
		model.addAttribute("list", list);

		//跳转到freemarker页面: list.ftl
		return "list";
	}
}

在Controller把数据传递到FreeMarker模板渲染

3 编写FreeMarker模板文件

FreeMarker模板文件必须放在/resources/templates目录下,后缀名为.ftl,内容如下:

<html>
	<title>一点教程网-用户列表展示</title>
	<meta charset="utf-8"/>
	<body>
		<h3>用户列表展示</h3>
		<table border="1">
			<tr>
				<th>编号</th>
				<th>姓名</th>
				<th>年龄</th>
			</tr>
			<#list list as user>
			<tr>
				<td>${user.id}</td>
				<td>${user.name}</td>
				<td>${user.age}</td>
			</tr>
			</#list>
		</table>
	</body>
</html>

4 运行测试

http://localhost:8080/list

 

源码下载:https://pan.baidu.com/s/10WaOAfrWHG-v2M8QFe2zMA

热门文章

优秀文章