1.創建一個maven項目
2.添加所需要的依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
3.寫一個接口,返回到src/main/resources/templates/test.ftl頁面(freemarker默認模板後綴爲ftl,默認路徑是src/main/resources/templates,可以在application.properties中更改配置)
@RestController
@RequestMapping("/test")
public class Test {
@SuppressWarnings("all")
@RequestMapping("/fun1")
public ModelAndView fun(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("/test");
mv.addObject("name","vhukze");
mv.addObject("sex",1);
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
mv.addObject("list", list);
return mv;
}
}
配置信息
## Freemarker 配置
##模版存放路徑(默認爲 classpath:/templates/)
spring.freemarker.template-loader-path=classpath:/templates/
##是否生成緩存,生成環境建議開啓(默認爲true)
spring.freemarker.cache=false
##編碼
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
##content-type類型(默認爲test/html)
spring.freemarker.content-type=text/html
## 設定所有request的屬性在merge到模板的時候,是否要都添加到model中(默認爲false)
spring.freemarker.expose-request-attributes=false
##設定所有HttpSession的屬性在merge到模板的時候,是否要都添加到model中.(默認爲false)
spring.freemarker.expose-session-attributes=false
##RequestContext屬性的名稱(默認爲-)
spring.freemarker.request-context-attribute=request
##模板後綴(默認爲.ftl)
spring.freemarker.suffix=.html
4.書寫test.ftl文件
<html>
<body>
<h2>Hello World!</h2>
${name}
<#if sex=1>
女
<#else>
男
</#if>
<#list list as num>
${num}
</#list>
</body>
</html>
跟EL表達式一樣的取值 ${}
判斷語句 <#if> <#elseif > <#else> </#if>
遍歷集合 <#list (域中的變量名) as (取出值的臨時變量名)> </#list>
這個就相當於java中的forEach語句
for (String num : list) {
System.out.println(num);
}
訪問接口方法映射路徑