spring boot 使用velocity、freeMarker模板建立html頁面返回給前端
阿新 • • 發佈:2019-01-10
簡單幾步,實現在spring boot中使用velocity或freeMarker模板構造頁面後返回給前端:
1、引入依賴和建立templates目錄:
Velocity:http://blog.csdn.net/clementad/article/details/51819647
FreeMarker:http://blog.csdn.net/clementad/article/details/51942629
2、建立模板檔案:
一個對應於錯誤的頁面(ulr輸入錯誤時自動輸出這個頁面,檔名:error.vm或error.ftl):
4、測試:
瀏覽器中輸入url:http://localhost:8082/web/hi
結果:
1、引入依賴和建立templates目錄:
Velocity:http://blog.csdn.net/clementad/article/details/51819647
FreeMarker:http://blog.csdn.net/clementad/article/details/51942629
2、建立模板檔案:
建立兩個檔案,一個對應於正常的頁面,檔名:
Velocity:welcome.vm
FreeMarker:welcome.ftl
<!DOCTYPE html> <html> <body> <h4>親愛的${toUserName},你好!</h4> <p style="color:blue;"> ${message}</p> 祝:開心! </br> ${fromUserName} </br> ${time} </body> </html>
一個對應於錯誤的頁面(ulr輸入錯誤時自動輸出這個頁面,檔名:error.vm或error.ftl):
<!DOCTYPE html>
<html>
<body>
<p>有錯誤: ${status} ${error}</p>
</body>
</html>
3、Controller程式碼:package com.xjj.web.controller; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.xjj.util.XDateUtils; @Controller @RequestMapping("/web") public class WebController { @RequestMapping("/hi") public String hi(Map<String, Object> model) { model.put("time", XDateUtils.nowToString()); model.put("message", "這是測試的內容。。。"); model.put("toUserName", "張三"); model.put("fromUserName", "老許"); return "welcome"; //自動尋找resources/templates中名字為welcome.vm的檔案作為模板,拼裝後返回 } }
4、測試:
瀏覽器中輸入url:http://localhost:8082/web/hi
結果:
如果輸入一個不存在的url,比如http://localhost:8082/web/hello,結果如下:
附: