springboot整合freemarker
1.创建springboot项目加入freemarker依赖和web依赖
2.查看依赖是否导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.创建实体类
4.创建controller
@Controller
public class UserController {
@GetMapping("/index")
public String index(Model model){
List<User>users=new ArrayList<>();
for (int i = 0; i <10 ; i++) {
User user=new User();
user.setId((long) i);
user.setUsername("小羊"+i+"号");
user.setAddress("翻斗大街" + i+"号");
users.add(user);
}
model.addAttribute("users",users);
return "index";
}
}
注意:@Controller不要写错了。
5。创建html更改后缀
freemarker默认访问后缀是ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>用户编号</td>
<td>用户姓名</td>
<td>用户地址</td>
</tr>
<#list users as user>
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.address}</td>
</tr>
</#list>
</table>
</body>
</html>
6.application.properties设置路径,不设置路径放在templates路径下会疯狂报500的错误
#HttpServletRequest的属性是否可以覆盖controller中model的同名项
spring.freemarker.allow-request-override=false
#HttpSession的属性是否可以覆盖controller中model的同名项
spring.freemarker.allow-session-override=false
#是否开启缓存
spring.freemarker.cache=false
#模板文件编码
spring.freemarker.charset=UTF-8
#是否检查模板位置
spring.freemarker.check-template-location=true
#Content-Type的值
spring.freemarker.content-type=text/html
#是否将HttpServletRequest中的属性添加到Model中
spring.freemarker.expose-request-attributes=false
#是否将HttpHttpSession中的属性添加到Moldel中
spring.freemarker.expose-session-attributes=false
#模板文件后缀
spring.freemarker.suffix=.ftl
#模板文件的位置
spring.freemarker.template-loader-path=classpath:/templates/
ing.freemarker.suffix=.ftl
#模板文件的位置
spring.freemarker.template-loader-path=classpath:/templates/
访问:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210317172506947.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMwODkzNjM1,size_16,color_FFFFFF,t_70)