前言
FreeMarker是一种Java模板引擎,类似jsp、themleaf,FreeMarker适合用于页面伪静态化,方便爬虫爬取,比较适用于官网。
如何使用?
1.pom文件引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.在application.yml文件中配置参数
server:
port: 8080
spring:
#配置freemarker
freemarker:
template-loader-path: classpath:/templates
charset: UTF-8
check-template-location: true
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
suffix: .ftl
#关闭缓存,及时刷新,上线需要改成true
cache: false
3.在resources文件夹下新建templates,在templates文件夹下新建index.ftl文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试free marker</title>
</head>
<body>
<h1>${userName},Welcome to Freemaker</h1>
</body>
</html>
4.编写Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class Ldkj_FreeMarkerController {
@RequestMapping("/testFree")
public ModelAndView testFree(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("userName","小诸葛");
return modelAndView;
}
}
5.启动项目,在地址栏输入:http://localhost:8080/testFree访问,访问结果如下图所示。