當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot_web开发-thymeleaf语法
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot_web开发-thymeleaf语法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們看一下Thymeleaf的自動配置規則,我們得按照規則用起來,這里有一個自動配置,這里專門有一個thymeleaf,Thymeleaf的自動配置,ThymeleafAutoConfiguration,自動配置不用看了,無非就是給里面添加一些組件,他有好多Thymeleaf2的,但是判斷不生效,視圖解析器添加組件,我們主要看默認規則,默認規則都在ThymeleafProperties里面,來看什么默認規則呢,@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");public static final String DEFAULT_PREFIX = "classpath:/templates/";public static final String DEFAULT_SUFFIX = ".html";照著他就直接用起來了,首先默認規則有一個默認的前綴,"classpath:/templates/",還有默認的后綴,前后綴就是我們視圖解析的代名詞,然后也是通過它我們就知道,只要我們把html頁面,放在類路徑下的templates里面,然后thymeleaf就能夠幫我們自動渲染了,那我們就直接來看一下,比如我來寫一個請求,如果我們以前寫success,現在我們引入了thymeleaf模板引擎,我們要去success頁面,thymeleaf默認在這拼,相當于在類路徑下的templates里面,給你找到success,還得拼一個后綴htmlclasspath:/templates/success.html為了能達到目的地,我們就在這寫一個success.html我們來發送這個success請求,看我們的模板引擎是不是來到success頁面localhost:8080/success
package com.learn.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello1() {return "hello controller";}@RequestMapping("/success")public String success() {// classpath:/templates/success.htmlreturn "success";}}
thymeleaf我們來參照他的文檔https://www.thymeleaf.org/他這里有3.0.9版本和2.1.6版本,同時使用,這里也有對thymeleaf的簡單介紹,它是現代的JAVA服務端的引擎hymeleaf is a modern server-side Java template engine for both web and standalone environments.特點是自然的模板語言,寫法就比較像html的語法格式,我們主要來看他的文檔Thymeleaf 3.0https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf體會一下thymeleaf的使用,我們就以一個最常用的場景,比如我們要發success請求,來到這個頁面,查出數據在頁面展示,如果是我們的JSP頁面就簡單多了,這個數據會放在我們請求域中,我想去success頁面取值怎么取啊https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html如果是以前JSP,就直接${hello}就完事,現在不是JSP,要按照thymeleaf的語法來,他語法是什么就得來說一下,首先我們要用thymeleaf,你得在html導入一個thymeleaf的名稱空間,示例里面把這段復制<html xmlns:th="http://www.thymeleaf.org">xmlns:th="http://www.thymeleaf.org"當然你也可以不導,不導的話就沒有語法提示了,導入的作用就是為了語法提示,我們使用的第一步,導入thymeleaf的名稱空間,第二步我們就可以使用thymeleaf的語法了,怎么使用呢,假設我這里有一個div,我們想在這里取出hello的值,th:text,意思就是文本內容,${hello},來訪問一下hello請求,看能不能取出來呢,我們來訪問一下,發現也取出來了http://localhost:8080/success
@RequestMapping("/success")public String success(Map<String,Object> map) {// classpath:/templates/success.htmlmap.put("hello", "您好");return "success";}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>成功!</h1><div th:text="${hello}"></div></body>
</html>
而且這樣取值是有很大好處的,我們來給大家看一下,這是顯示歡迎信息,如果這個頁面不經過模板引擎解析,來直接訪問,這個顯示的是前端自己寫的數據,如果經過了模板引擎解析訪問,把它就替換成后臺的數據,這個前后端分工起來就更好用了,接下來就詳細來看一下thymeleaf的語法規則,thymeleaf的語法規則是什么樣的呢
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>成功!</h1><div th:text="${hello}">這是顯示歡迎信息</div></body>
</html>
語法規則,首先就是第一個,th:text我們開始說,它是來改變我們當前元素里面的文本內容的,我們可以用th任意屬性,這個什么意思啊,由于前端好多東西都有默認值,比如這個div他有id,他有他的默認id,叫div01,他還有他默認的class,我們就叫myDiv,而這些值我們想改怎么改呢,我都可以用th:id的方式,如果我們能夠取出一個值,比如${hello},然后th:class的方式,我都能改掉他的值,${hello},這就是我們使用th任意屬性替換原生屬性的值,我們可以給大家看一下,id,class都是我們替換來的值
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>成功!</h1><div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">這是顯示歡迎信息</div></body>
</html>
所以我們有th任意屬性,我們th語法到底有多少呢,我們可以參照一下官方文檔,在官方文檔的第10章,屬性的優先級,Attribute Precedence,這里列舉了這些屬性,那個是先執行,哪個是后執行,我們可以把它截一個圖,說一下每一個都是怎么用的
包括我們可以跟JSP類比一下,第一個叫Fragment inclusion,我們就叫片段包含,來做片段包含操作的,一個是插入,一個是替換,就類似于jsp:include標簽一樣,我們抽取公共的片段,可以包含進來,然后第二個我們來看,叫Fragment iteration,這個是我們來做遍歷的,th:each,類似于jsp里面用的c:forEach,就是這個,th:if,th:unless,th:switch,th:case是來做判斷的,是來做條件判斷的,條件判斷就類似于以前的c:if等等,這里還有一個Local variable definition,做聲明變量的,就類似于我們以前的c:set標簽一樣,可以來設置一些變量,還有一個General attribute modification,這個是來做屬性修改的,這個屬性修改啊,他這里叫th:attr,th:attrprepend,th:attrappend,這是來做任意屬性修改的,我們以前來做屬性修改,都是來替換值的,支持prepend,給他前面添加,給他append,給他后面來追加內容的,支持這些功能的,還有一個是Specific attribute modification,這就是來修改我們指定屬性的,就是修改我們默認的值,還有我們使用的th:text,這個叫標簽體里面文本內容的,這里有一個th:text,還有一個th:utext,一個是轉義,一個是不轉義,utext它是不轉義,不轉義特殊字符,這樣的話我們文本里面,H1標簽就是一個大標題,但是上面的th:text它是轉義的,相同的如果我們寫了一個html片段,用th:text展示出來,那片段就當成普通字符串了,才會給你在頁面打印h1,但是不會給你轉義特殊字符,還有個叫Fragment specification,這個片段能夠包含進來,就在這聲明一下,我們后來再說就行了,那這個就是我們th的整個語法
但是我們再來看,在th里面呢,需要寫一些表達式,表達式能寫什么,我們能寫th來做功能標簽,我們能寫哪些表達式,我們官方文檔里面也有說,這里有一個標準的表達式語法,有非常多的表達式語法,給你來做一個簡單的總結
But there are more types of expressions, and more interesting details to learn about the
ones we already know. First, let’s see a quick summary of the Standard Expression
features:Simple expressions:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
Literals
Text literals: 'one text', 'Another one!',…
Number literals: 0, 34, 3.0, 12.3,…
Boolean literals: true, false
Null literal: null
Literal tokens: one, sometext, main,…
Text operations:
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:
Binary operators: +, -, *, /, %
Minus sign (unary operator): -
Boolean operations:
Binary operators: and, or
Boolean negation (unary operator): !, not
Comparisons and equality:
Comparators: >, <, >=, <= (gt, lt, ge, le)
Equality operators: ==, != (eq, ne)
Conditional operators:
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
No-Operation: _
這些表達式語法我們來看一下,我們能寫哪些表達式,${},*{},#{},@{},~{},這都是什么意思,表達式語法,第一個${},我們之前是用來獲取變量值的,每一個怎么用呢,每一個我們來參照文檔來看一下,標準表達式語法,Variables變量,${}是用來獲取值,底層就是OGNL表達式,既然是OGNLWe already mentioned that ${...} expressions are in fact OGNL (Object-Graph Navigation Language) expressions executed on the map of variables contained in the context.各種高大上的往下看,能怎么用呢,下面有各種例子,比如我們可以調用對象的屬性,https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#variables/** Access to properties using the point (.). Equivalent to calling property getters.*/
${person.father.name}包括調屬性的時候可以這樣來使用/** Access to properties can also be made by using brackets ([]) and writing * the name of the property as a variable or between single quotes.*/
${person['father']['name']}/** If the object is a map, both dot and bracket syntax will be equivalent to * executing a call on its get(...) method.*/
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}如果map中的key有空格,我們也可以這么來寫,/** Indexed access to arrays or collections is also performed with brackets, * writing the index without quotes.*/
${personsArray[0].name}數組中來取,/** Methods can be called, even with arguments.*/
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}包括我們進行方法調用,包括方法我們還能給她傳一個參數,這個就是我們OGNL表達式,不僅能調屬性,獲取對象的屬性,這是最基本的功能,然后他還能調用方法,接下來他還有一些功能,下面還有一個Expression Basic Objects,我們表達式里邊還能寫"#.",#是內置的一些基本對象,使用內置的基本對象,內置的對象都是什么呢,#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.一個叫ctx,當前上下文對象,當前上下文的變量值,包括locale代表區域信息的,如果是WEB環境,有我們的request,response,session,servletContext,它能夠使用這幾個內置對象,他還能用什么呢,包括內置對象怎么用,這一塊也有文檔,可以點進去,Established locale country: <span th:text="${#locale.country}">US</span>.如果我們要用我們國家的區域信息,哪個國家,區域代號,他的使用附錄都在這,You can read the full reference of these objects in Appendix A.https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects比如我們獲取請求參數的這個值,/** ============================================================================* See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap* ============================================================================*/${param.foo} // Retrieves a String[] with the values of request parameter 'foo'
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}
...通過size我們知道請求參數中有多少個參數,包括請求參數是不是為空一大堆,還有我們從session獲取值,我來舉一個例子,例子都在附錄里面,除了基本對象外,還有工具對象,Expression Utility Objects,內置的一些工具對象,工具對象會增強一些功能,是哪個對象呢,Besides these basic objects, Thymeleaf will offer us a set of utility objects that will
help us perform common tasks in our expressions.#execInfo: information about the template being processed.
#messages: methods for obtaining externalized messages inside variables expressions,
in the same way as they would be obtained using #{…} syntax.
#uris: methods for escaping parts of URLs/URIs
#conversions: methods for executing the configured conversion service (if any).
#dates: methods for java.util.Date objects: formatting, component extraction, etc.
#calendars: analogous to #dates, but for java.util.Calendar objects.
#numbers: methods for formatting numeric objects.
#strings: methods for String objects: contains, startsWith, prepending/appending, etc.
#objects: methods for objects in general.
#bools: methods for boolean evaluation.
#arrays: methods for arrays.
#lists: methods for lists.
#sets: methods for sets.
#maps: methods for maps.
#aggregates: methods for creating aggregates on arrays or collections.
#ids: methods for dealing with id attributes that might be repeated
(for example, as a result of an iteration).我們就來結合文檔的演示,這個就是我們內置的工具對象,有演示在附錄里打開,You can check what functions are offered by each of these utility objects in the Appendix B.https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects我們要使用numbers這個工具類,我們來做一些事情/* * Set minimum integer digits.* Also works with arrays, lists or sets*/
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}String工具類可以把他轉成toString,/** Null-safe toString()*/
${#strings.toString(obj)} 下面也可以調用startWith方法,/** Check whether a String starts or ends with a fragment* Also works with arrays, lists or sets*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*有非常多的用法,這都有示例,我們都可以來對照使用,這個就是我們${},用的最多也是最強大的表達式,接下來我們再來看第二個,叫*{},這個叫變量的選擇表達式,這個東西是什么呢,4.3 Expressions on selections (asterisk syntax)*{}是什么呢,Not only can variable expressions be written as ${...}, but also as *{...}.不僅變量表達式可以寫成${},還可以寫成*{},他和${}在功能上是一樣的,只是有一個補充功能,比如我們有一個tb:object,我們取出一個對象,session里面取出user對象,我們先把tb:object對象重寫,以后我們要用user對象的值,我們就可以在當前的div里面,星號就代表我剛才的對象,然后我們直接獲取對象里的屬性就行了,這個就類似于寫session.user.firstName<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div><div><p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p><p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p><p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>補充使用就是,就是配合th:object一起使用的,以后我們要獲取里面的值呢,就可以直接這么來做了,這個都有文檔片段,我們就參照這個文檔,他都不難,我們就參照文檔,我們來做就行了,我們再通過實驗來深化使用,還有一個叫#{},這是干什么呢,一個叫Message,Message它是來取國際化內容的,包括@{},它是來幫我們定義url鏈接的,用它定義url有什么好處呢,我們可以在下面看到示例,比如這里就有一個示例,<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a><!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a><!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>如果要傳多個變量,If several parameters are needed, these will be separated by commas:@{/order/process(execId=${execId},execType='FAST')}包括我們來看下面,前面都不寫了,我們直接寫一個杠,片段引用的表達式,我們文檔里面也有Fragments,我們要插入一個片段文檔,我們要用~{},我們在實驗里面再說,<div th:insert="~{commons :: main}">...</div>這就是我們五種表達式,如果要用thymeleaf模板引擎,知道何時用哪種表達式就行了,接下來就是其他的一些用法了,你可以用字面量,比如普通的字符串,數字,包括多個數據用逗號隔開,文本操作,這里還有數學運算,他支持數學運算,表達式里邊就會用這些數學運算,包括還有布爾運算,什么并且什么,什么或什么,包括還支持比較運算,比如有一些特殊字符,用后面這些來替代,條件運算,if-then,這個就是我們三元運算符,前面是一個條件
跟遍歷有關Iteration,這一塊我們看下面的示例,他這里有一段代碼https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#iterationpublic void process(final HttpServletRequest request, final HttpServletResponse response,final ServletContext servletContext, final ITemplateEngine templateEngine)throws Exception {ProductService productService = new ProductService();List<Product> allProducts = productService.findAll(); WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());ctx.setVariable("prods", allProducts);templateEngine.process("product/list", ctx, response.getWriter());}比如他用了一個Service查了一些數據,用prods保存起來,他用的是th:each標簽,把我們要遍歷的數據取出來${prods}<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><title>Good Thymes Virtual Grocery</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><link rel="stylesheet" type="text/css" media="all" href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" /></head><body><h1>Product list</h1><table><tr><th>NAME</th><th>PRICE</th><th>IN STOCK</th></tr><tr th:each="prod : ${prods}"><td th:text="${prod.name}">Onions</td><td th:text="${prod.price}">2.41</td><td th:text="${prod.inStock}? #{true} : #{false}">yes</td></tr></table><p><a href="../home.html" th:href="@{/}">Return to home</a></p></body></html>每一個數據要用什么變量名,他在冒號里面用了變量名,冒號后面要遍歷的是集合,以后就用變量名取出這個數據,那我們也來這么遍歷,th:each每次遍歷都會生成當前這個標簽,我如果是這種遍歷,12 Inlining行內寫法,我們就可以用[[...]] or [(...)]的方式,這兩個有啥區別呢,其實[[...]]就是th:text,[(...)]就是th:utext,Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.Note that, while [[...]] corresponds to th:text (i.e. result will be HTML-escaped), [(...)] corresponds to th:utext and will not perform any HTML-escaping. So with a variable such as msg = 'This is <b>great!</b>', given this fragment:localhost:8080/success
package com.learn.controller;import java.util.Arrays;
import java.util.Map;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello1() {return "hello controller";}@RequestMapping("/success")public String success(Map<String,Object> map) {// classpath:/templates/success.htmlmap.put("hello", "<h1>您好</h1>");map.put("users", Arrays.asList("張三","李四","王五"));return "success";}}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>成功!</h1><div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">這是顯示歡迎信息</div><hr/><div th:text="${hello}"></div><div th:utext="${hello}"></div><hr/><!-- th:each每次遍歷都會生成當前這個標簽:3個h4 --><h4 th:text="${user}" th:each="user : ${users}"></h4><hr/><h4><span th:each="user : ${users}">[[${user}]]</span></h4></body>
</html>
?
總結
以上是生活随笔為你收集整理的SpringBoot_web开发-thymeleaf语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot_web开发-引入t
- 下一篇: SpringBoot_web开发-【实验