以前在Controller包中簡單處理了URL的Path參數。包括PathVariable和RequestParam。html
可是網頁是很複雜的,裏面有不少圖片,元素。若是將這些都寫在Controller層,會使其過於龐大。所以,能夠把這些網頁的處理放到一個文件裏面,而後在Controller裏面返回這個文件,這個文件就叫模板。這樣使得Controller文件很簡潔。前端
以前的程序中,每次都在public返回函數前面加@ResponseBody,如今我註釋掉這個註解。web
顯示爲:app
Error resolving template [Hello_World], template might not exist or might not be accessible by any of the configured Template Resolvers:意思是模板Hello_World不存在或者不能被訪問。ide
經過資料知道,@ResponseBody讓返回結果直接寫入Http正文中。不加@ResponseBody,return時,跳轉到templates包下找return的指定的文件,返回文件的內容。參考資料傳送門。函數
例子:ui
1.在Controller包文件中,加入下列代碼,表示當訪問/hello路徑時,返回Hello.html(.html能夠省略)文件。spa
1 @RequestMapping(value = {"/hello"}) 2 public String Hello_World() { 3 return "Hello"; 4 }
2.在Templates包下面建立Hello.html文件。Hello.html文件內容以下:.net
1 <html> 2 <head> 3 <title>Welcome!</title> 4 </head> 5 <body> 6 <h1>Welcome</h1> 7 </body> 8 </html>
顯示結果:prototype
什麼是Thymeleaf?
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
Tymeleaf具體幹了什麼?
It builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype.
Thymeleaf能處理哪些模板模式?
Out-of-the-box, Thymeleaf allows you to process six kinds of templates, each of which is called a Template Mode:HTML,XML,TEXT,JAVASCRIPT,CSS,RAW.
總結:經過上面的基本解釋能夠推導。前端語言跟模板語言徹底就是不一樣的概念。HTML有本身的語法,而Thymeleaf有本身的語法。例如:
HTML註釋用<!-- -->
Thymeleaf中用<!--/*--> <!--*/-->
模板語言在這裏的做用就是,將Controller的數據寫道HTML文件中。
Thymeleaf經常使用語法傳送門
1.Controller部分定義一個aaa變量,值爲"naive"。
1 @RequestMapping(path = {"/hello"}) 2 public String Hello_World(Model model) { 3 model.addAttribute("aaa", "naive"); 4 return "Hello"; 5 }
2.模板部分使用aaa變量:
1 <html> 2 <head> 3 <title>Welcome!</title> 4 </head> 5 <body> 6 <h1>Welcome</h1> 7 <p th:text="${aaa}" /> 8 </body> 9 </html>
輸出結果:
我的感受這個模板語言有點冗餘,<p th:text="${aaa}" />這麼多代碼才能顯示一個變量。期待打臉。