作者:江夏
| 知乎:www.zhihu.com/people/1024…
| GitHub:github.com/JiangXia-10…
| CSDN:blog.csdn.net/qq_4115394…
| 公众号:1024笔记
本文一共1289字,阅读时长6分钟
1、引言
关于springboot项目的创建可以看下面这篇文章,这里不进行叙述,可以参考之前的文章SpringBoot入门:使用IDEA和Eclipse构建第一个SpringBoot项目。
2、Freemarker模板
首先在pom文件中引入freemarker的依赖,代码如下:
<!-- Spring Boot Freemarker 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
然后在com.example.demo文件夹下新建一个controller文件夹,新建FreemarkerController类,代码如下:
package com.example.demo.controller;
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 FreemarkerController {
@RequestMapping(value="/freemarker",method = RequestMethod.GET)
public String freemarker(Model model) {
model.addAttribute("name", "李青");
model.addAttribute("age", 22);
model.addAttribute("id", 223);
return "freemarker";
}
}
在application.yml文件中配置freemarker,修改的yml文件,新建默认的是application文件,yml配置如下:
#yml和property文件功能一样都是配置设置,比如数据库、端口号等等,但是yml的
#结构是树状结构比较明朗,而且相同的内容因为是树状展示不用重复写
#但是如果项目中两个文件同时存在则优先加载property,yml的配置无效
#注意,eclipse中yml文件用tab键进行缩进,会报错。
spring
freemarker:
# prefix: classpath:/templates/
suffix: .ftl
content-type: text/html
template-loader-path: classpath:/templates
在templates文件夹下新建freemarker.ftl文件,代码如下:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<body>
姓名:${name}<br><br>
年龄:${age}<br><br>
编号:${id}<br><br>
</body>
</html>
启动项在浏览器地址栏输入,http://localhost:8080/freemarker 页面结果如下:
freemarker页面模板创建完成!
3、Thymeleaf模板
同样在pom文件中引入thymeleaf依赖,代码如下:
<!--引入thymeleaf的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在controller文件夹下新建ThymeleafController类,代码如下
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafController {
@RequestMapping("/thymeleaf")
public String test(Model model) {
model.addAttribute("name", "李青");
model.addAttribute("age", 22);
model.addAttribute("id", 223);
return "thymeleaf";
}
}
在application.yml文件中配置thymeleaf,代码如下:
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
cache: false
content-type: text/html
然后在templates文件夹下新建thymeleaf.html页面文件,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
姓名:<input type="text" th:value="${name}"><br/>
年龄:<input type="text" th:value="${age}"><br/>
编号:<input type="text" th:value="${id}"><br/>
</body>
</html>
启动项目,在浏览器地址栏输入,http://localhost:8080/thymeleaf ,页面结果如下:
thymeleaf页面模板创建完成!
总结
本文主要介绍了springboot如何使用freearker和thymeleaf模板高效的创建页面。
最后欢迎关注公众号:1024笔记,获取更多的相关文章,还可以免费获取海量学习资源(涵盖视频、源码、文档)!
相关推荐: