spring boot thymeleaf簡單使用
阿新 • • 發佈:2018-12-18
spring4推薦使用thymeleaf模板進行開發,剛好最近需要使用,一起來學習一下
1.加入maven依賴
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.簡單配置application.yml
spring: thymeleaf: mode: LEGACYHTML5 prefix: classpath:/templates/ suffix: .html cache: false encoding: utf-8
3.編寫html
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <META HTTP-EQUIV="pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> <META HTTP-EQUIV="expires" CONTENT="0"> <head th:fragment="head"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>title</title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="Access-Control-Allow-Origin" content="*"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="format-detection" content="telephone=no"> <link rel="icon" href="favicon.ico"> <link rel="stylesheet" th:href="@{/layui/css/layui.css}"> <link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" /> <link rel="stylesheet" media="all" th:href="@{/css/main.css}"/> <script src="" th:src="@{/js/jquery-1.8.0.min.js}"></script> <script type="text/javascript"> var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/"; </script> </head> <body> </body> </html>
我這裡寫的是一個簡單的公共的html用到了th:fragment="head"用來定義用於載入的塊,在我們需要使用的頁面使用
<head th:replace="header :: head">就可以替換head標籤裡的內容,當然還可以使用th:include
th:include 和 th:replace的區別
th:include和th:replace都可以引入模組,兩者的區別在於 th:include:引入子模組的children,依然保留父模組的tag。 th:replace:引入子模組的所有,不保留父模組的tag。
在js中還寫了一串js程式碼,用來獲取專案名
<script type="text/javascript"> var WEB_ROOT = '[[${#httpServletRequest.contextPath}]]' + "/"; </script>
這樣的話需要在調後臺服務的地方拼寫WEB_ROOT就不用擔心把路徑搞錯了
4.編寫controller
@Controller @RequestMapping("/test") public class TestController { @RequestMapping("/toIndex") public String toIndex(){ return "index"; } }
在controller裡面返回檢視就可以了