SpringBoot集成FreeMarker
(1)在pom.xml中添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
(2)在springboot的配置文件application.proeprties中配置freeamarker
#启用freemark。默认为false——不使用freemarker。
spring.freemarker.enabled=true
#指定freemarker模板文件的后缀
spring.freemarker.suffix=.ftl
这一步是必须的,但很多教程上都没写。
(3)在controller中转发到freemarker页面,并传递数据
@Controller
public class UserController {
@RequestMapping("/user")
public String handler(Model model){
model.addAttribute("username", "chy");
return "user/user_info";
}
}
@RestController用来传回json数据,一般用来写与前端交互的接口。普通的controller用@Controller就行了。
(4)在reosurces下新建文件夹templates,templates下新建.ftl文件(freemark文件),使用controller传来的数据。
springboot默认模板存放路径是resources\templates,由于user有多个视图,我们在templates下新建文件夹user来存放。
user下新建html文件user_info.html,Shif+F6重命名为.ftl文件。
<body> <#--取数据--> ${username} </body>