springboot整合thymeleaf(精簡版)

1.springboot整合thymeleaf(精簡版)

1.1引入依賴

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

1.2 在resources下創建一個templates文件夾(文件名稱不能寫錯)

該文件夾用來放置靜態資源
Alt

1.3創建controller類

注意:最好將數據對象封裝成一個Map,便於前臺數據獲取。

import com.mayday.portals.pojo.Article;
import com.mayday.portals.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PortalsController {
    @Autowired
    private ArticleService articleService;

    @GetMapping("/portals.html")
    public String toPortalsPage(Model model) {
        List<Article> articles = articleService.listAll();
        Map<String, List<Article>> models = new HashMap<>();
        models.put("articles", articles);
        //準備數據模型
        model.addAllAttributes(models);
        return "portals";
    }
}

1.4 創建靜態頁面

引入thymeleaf依賴
Alt
Alt

1.5啓動

在瀏覽器中即個訪問
Alt
在開發環境中最好將thymeleaf的緩存關閉,避免不必要的麻煩。
Alt

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章