springboot整合freemarker,首先加入依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--发现spring-boot-starter-freemarker依赖中包括spring-boot-starter-web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
定义Controller类
@Controller
public class UserController {
@GetMapping("/reg")
public String reg(){
return "reg";
}
@GetMapping("/logout")
public String logout(Model model){
model.addAttribute("username","zhihao.miao");
model.addAttribute("logout","true");
return "logout";
}
}
启动类:
package com.zhihao.miao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
因为springboot整合freemarker默认的会读取classpath:/templates/下的模版文件,所以一般我们将模版文件放入到classpath:/templates/下即可。
reg.ftl文件内容:
package com.zhihao.miao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
logout.ftl:
<h1>logout page</h1>
<h1>username is ${username}</h1>
<h1>logout is ${logout}</h1>
启动Application类并启动
也可以修改模版文件的位置,可以使用
spring.freemarker.templateLoaderPath=classpath:/ftl
将上面二个模版文件放在ftl文件夹下重新测试一下即可。
源码查看:
org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties