前言
spring-boot 支持多種模版引擎包括:
1,FreeMarker
2,Groovy
3,Thymeleaf (Spring 官網使用這個)
4,Velocity
5,JSP (貌似Spring Boot官方不推薦,STS創建的項目會在src/main/resources 下有個templates 目錄,這里就是讓我們放模版文件的,然后並沒有生成諸如 SpringMVC 中的webapp目錄)
小項目
1. 導入依賴
<!-- web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ... --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- FreeeMarker模板引擎所需依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2.配置 application.properties
# FreeeMarker 模板引擎配置 #指定HttpServletRequest的屬性是否可以覆蓋controller的model的同名項 spring.freemarker.allow-request-override=false #是否開啟template caching. spring.freemarker.cache=false #是否檢查templates路徑是否存在. spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html # 設定所有request的屬性在merge到模板的時候,是否要都添加到model中. spring.freemarker.expose-request-attributes=false # 設定所有HttpSession的屬性在merge到模板的時候,是否要都添加到model中. spring.freemarker.expose-session-attributes=false #設定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用 spring.freemarker.expose-spring-macro-helpers=false #spring.freemarker.request-context-attribute= #spring.freemarker.settings.*= #設定模板的前綴. #spring.freemarker.prefix= #設定模板的后綴. spring.freemarker.suffix=.ftl #設定模板的加載路徑,多個以逗號分隔,默認: [“classpath:/templates/”] spring.freemarker.template-loader-path=classpath:/templates/ #spring.freemarker.view-names= # whitelist of view names that can be resolved
3.模板頁面(HTML或FTL)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> Hello : ${msg} </body> </html>
4.編寫controller類,跳轉頁面
@Controller public class WebController { @RequestMapping("/index") public String index(Model model){ model.addAttribute("msg", "后台傳的數據..."); return "index"; } } 或 @RestController //@RestController=@Controller+@ResponseBody 官方推薦使用 public class WebController2 { @RequestMapping("/index2") public ModelAndView index(Model model){ model.addAttribute("msg", "后台傳的數據..."); return new ModelAndView("index"); } }
5.編寫啟動類
@SpringBootApplication public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class); } }
6.運行測試
項目結構
freemaker模板語法:http://freemarker.foofun.cn/index.html