FreeMarker入门
freemarker文件以.ftl为后缀
1.pom.xml中配置依赖,利用maven管理jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.写controller
@Controller public class ProductController { @RequestMapping(method = RequestMethod.GET, value = "/products") public String showAll(Model model) { List<Customer> customers = new ArrayList<Customer>(); customers.add(new Customer(1L, "c1", "a1", "133...")); customers.add(new Customer(2L, "c2", "a2", "133...")); customers.add(new Customer(3L, "c3", "a3", "133...")); model.addAttribute("products", customers); return "products"; } }
3.创建freemarker
在项目中的src/main/resources中的templates中创建*.ftl文件
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
放在<head>中,定义编码
Freemarker (https://freemarker.apache.org/)中有template模板,操作如下
点击红色框中的链接,选择下面的模板
将之copy进*.ftl文件中
eg.
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Welcome</title> </head> <body> <h1>Hello, FreeMarker!</h1> <p>成员:</p> <#list products as product> <li>${product.id}/${product.name}</li> </#list> </body> </html>
4.测试
运行项目中src/main/java下的XXXApplication,使用测试工具Restlet Client或直接在页面上测试
*:补充
FreeMarker 自有的指令,不需要引标签库
条件:<if></if>
循环:<#list></#list>
springMVC 封装了jsp和freemarker,写好控制器,将数据放入model,页面获取即可