在咱們開發Web應用的時候,須要引用大量的js、css、圖片等靜態資源。
Spring Boot的默認位置是resources/staticcss
各類模版的頁面,此次咱們選用Thymeleaf
Spring Boot的默認位置是resources/templateshtml
在以前的示例中,咱們都是經過@RestController來處理請求,因此返回的內容爲json對象。當咱們須要頁面的時候使用@Controller,使其尋找模版頁面java
對於已存在的項目能夠在bulid.gradle加入git
compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-web')
至此Thymeleaf已經引入github
新建一個ThymeleafCtrl類web
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller//這是一個控制器 public class ThymeleafCtrl { @RequestMapping("/") public String hello(Model model) { model.addAttribute("hello","hello thymeleaf");//添加一個值爲"hello thymeleaf"的hello變量到視圖 return "hello";//在templates下尋找hello.html } }
在resources/templates建立一個hello.html頁面spring
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><!-- xmlns:th="http://www.thymeleaf.org" 減小ide報錯,能夠沒有 --> <head> <meta charset="UTF-8"/> <title>Hello</title> </head> <body> <h1 th:text="${hello}">LieRabbit</h1><!-- 使用hello變量 --> <img src="lierabbit.jpg"/> </body> </html>
在resources/static添加lierabbit.jpgjson
更多的Thymeleaf的語法請前往官網查看文檔(http://www.thymeleaf.org/doc/...)
源碼地址:https://github.com/LieRabbit/...
原文地址:https://lierabbit.cn/2018/01/...app