SpringBoot學習筆記(6)——SpringBoot整合Freemarker
1. 創建項目
2. 修改pom,添加座標
<dependencies>
<!-- springBoot的啓動器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- freemarker啓動器的座標 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
3. 編寫視圖
注意:springBoot要求模板形式的視圖層技術的文件必須要放到src/main/resources目錄下必須要一個名爲templates的文件夾中。
userList.ftl:
<html>
<head>
<title>展示用戶數據</title>
<meta charset="utf-9"></meta>
</head>
<body>
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<#list list as user >
<tr>
<td>${user.userid}</td>
<td>${user.username}</td>
<td>${user.userage}</td>
</tr>
</#list>
</table>
</body>
</html>
4. 創建Controller
@Controller
public class UserController {
/*
* 處理請求,產生數據
*/
@RequestMapping("/showUser")
public String showUser(Model model){
List<Users> list = new ArrayList<>();
list.add(new Users(1,"張三",20));
list.add(new Users(2,"李四",22));
list.add(new Users(3,"王五",24));
//需要一個Model對象
model.addAttribute("list", list);
//跳轉視圖
return "userList";
}
}
5. 創建啓動器
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6. 運行
運行App.java啓動SpringBoot,在瀏覽器端訪問localhost:8080/showUser