引入依賴css
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
添加application.properties配置html
spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html;charset=UTF-8 #設定全部request的屬性在merge到模板的時候,是否要都添加到model中. spring.freemarker.expose-request-attributes=true #定全部HttpSession的屬性在merge到模板的時候,是否要都添加到model中. spring.freemarker.expose-session-attributes=true #設定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用 spring.freemarker.expose-spring-macro-helpers=true #文件後綴 spring.freemarker.suffix=.ftl spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss spring.freemarker.settings.default_encoding=UTF-8
控制器返回頁面java
1 package com.xiaoping.house.controller; 2 3 import com.xiaoping.house.common.model.User; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.ModelMap; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 9 import java.util.List; 10 11 @Controller 12 public class HelloController { 13 @Autowired 14 private UserService userService; 15 @RequestMapping("/hello") 16 public String hello(ModelMap modelMap){ 17 List<User> userList = userService.getUsers(); 18 User one=userList.get(0); 19 modelMap.put("user",one); 20 return "hello"; 21 } 22 }
編寫模板引擎文件templates/hello.ftlweb
${user.name}
結構化佈局spring
靜態文件:resources/static/static/assetssession
抽取header,footer,nav,js,分頁app
common/common.ftlide
1 <#macro header> 2 <html lang="en-US"> 3 <head> 4 <meta charset="UTF-8"/> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta name="author" content="ThemeStarz"> 7 8 9 <link rel="stylesheet" href="/static/assets/css/toastr.css" type="text/css"> 10 11 12 13 <title>好房網</title> 14 </head> 15 </#macro> 16 <#macro footer> 17 18 </#macro>
頁面中引入header,footerspring-boot
//自動引入common文件,在applicaiton.properties配置 spring.freemarker.settings.auto_import=common/common.ftl as common
編寫頁面中自定義的部分佈局
//引入: <@common.header/>