springboot 集成freemarker
官方文档
配置详解
pom 依赖
<!-- web依赖包含springbmvc、tomcat 可以直接使用无需配置 -->
<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>
测试demo
创建Controller测试类
/**
* @author pillarzhang
* @date 2019-06-03
*/
@Controller
class FreemarkerController {
@RequestMapping("/index")
public String index(Model model){
model.addAttribute("name","hello pillar");
return "index";
}
}
application.properties
配置文件你可以选择不配置默认,也可以进行手动配置
选择默认时配置路径一定要写对,src/main/resources static(js,css等静态文件),templates(页面路径)注意是ftl后缀注意: springboot 2.2之前使用 ftl 后缀, 之后使用 ftlh 后缀。
Index.ftl文件如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>FreeMarker</title>
</head>
<body>
<h1>hello world</h1>
<h1 style="color: red">${name}</h1>
</body>
</html>
启动项目,输入地址http://localhost:8080/index显示如下则成功
application.properties
自定义配置
# freemarker start
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftlh
spring.freemarker.content-type=text/html; charset=utf-8
spring.freemarker.enabled=true
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.charset=UTF-8
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.tag_syntax=auto_detect
spring.freemarker.settings.locale=zh_CN
spring.freemarker.settings.date_format=yyyy-MM-dd
spring.freemarker.settings.time_format=HH:mm:ss
spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss
spring.freemarker.settings.number_format='0.##'
# end
application.yaml
案例自定义配置
spring:
freemarker:
request-context-attribute: request
suffix: .ftlh
content-type: text/html; charset=utf-8
enabled: true
cache: false
check-template-location: true
template-loader-path: classpath:/templates/
charset: UTF-8
expose-request-attributes: false
expose-session-attributes: false
settings:
template_update_delay: 0
tag_syntax: auto_detect
locale: zh_CN
date_format: yyyy-MM-dd
time_format: HH:mm:ss
datetime_format: yyyy-MM-dd HH:mm:ss
number_format: '0.##'
常见异常:
- 前端页面报 500错误。
- 后端错误如下:
2020-12-10 10:00:19.672 ERROR 9908 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause
版本问题: 本人使用的springboot2.2 版本, 需要将后缀修改为.ftlh, 即使我在配置文件中将
spring.freemarker.suffix=.html
, 测试后依然无效, 目前也没时间去查具体的原因,后期空闲下来在说吧, 或者哪位大神告诉我下,感谢!