在上一篇文章“SpringBoot整合视图技术:JSP篇”我给大家简单分享了一下在SpringBoot应用中如何使用JSP。今天,与大家分享的话题是如何整合Freemarker。
人不狠,话也不多!开撸~
1、在pom.xml文件中添加依赖,如下:
<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-freemaker</artifactId>
</dependency>
</dependencies>
2、修改SpringBoot核心配置文件application.yml,如下:
server:
port: 80
spring:
freemarker:
cache: false #开发时建议关闭缓存
charset: utf-8
check-template-location: true
content-type: text/html
enabled: true
suffix: .ftl
template-loader-path: classpath:/templates #配置模板所在目录
注意,在这里为了方便访问,我修改了端口号。
3、编写用于测试我们页面的的控制器,如下:
/**
* @Description Freemarker测试
* @Auther: 笑笑是一个码农
* @Date: 21:18 2019/11/4
*/
@Controller
public class FreemarkerController {
private static final String INDEX_PAGE = "index";
/**
* 跳转测试页面控制器
* @param map
* @return
*/
@GetMapping(value = "/index")
public String index(Map<String, String> map){
map.put("username","笑笑是一个码农");
return INDEX_PAGE;
}
}
4、编写测试页面index.ftl
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Freemarker</title>
</head>
<body>
<h1>${username}</h1>
</body>
</html>
仅仅是测试使用,我们的页面也不需要太过复杂,直接把值取出来展示即可。
5、最终的项目结构如下:
6、启动我们的SpringBoot应用,访问http://localhost/index,如下:
到此,我们我们就可以在SpringBoot应用中初步使用Freemarker了!
源码链接:
https://github.com/devilyang123/SpringBoot-Learning/tree/master/springboot-freemarker
欢迎关注我的个人公众号“笑笑是一个码农”,第一时间获取最新文章。
您的关注,就是支持我持续写作的最大动力!
还可以免费领取前后端全站学习视频资料呦~
个人微信号,如需添加微信,请备注来源,因为妈妈从小就告诉我不要随便跟陌生人聊天!(嘿嘿~)