搭建springboot-thymeleaf

  • 開發環境
  1. eclipse Mars.2 Release (4.5.2)
  2. maven 3.3.9
  3. jdk 1.8.0_171 3.jdk 1.8.0_171
  4. os win10
  • 環境搭建
  1. 創建maven工程
  2. 編輯pom.xml
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
</parent>
	
<dependencies>
        <dependency>
        <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
</dependencies>
  1. 編輯application.properties 進行thymeleaf配置
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
#熱部署文件,頁面不產生緩存,及時更新
spring.thymeleaf.cache=false
  1. 創建包目錄結構
    springboot-thymeleaf包目錄結構
  2. 編寫Controller層
@Controller
@RequestMapping("/user")
public class UserController {

	@RequestMapping("/list")
	public String listUser(Model model){
		List<User> userList = new ArrayList<User>();
		for (int i = 0; i < 10; i++) {
			userList.add(new User("id:" + i,"name:" + i));
		}
		
		model.addAttribute("users", userList);
		return "/user/list";
	}
}
  1. 編寫list.html文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
  <h2>用戶列表</h2>
  <div>
     <ul>
         <li  th:each="user:${users}">
              <span th:text="${user.id}"></span>-
             <span th:text="${user.name}"></span>-
         </li>
     </ul>
   </div>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章