Spring Boot Learning Record (ii) –thymeleaf template
tags (space delimited): Spring-boot
Since came to the company have not used JSP when the interface rendering, because the front and back end separation is not very good, but the template engine with more, thymeleaf the biggest advantage suffix HTML, is only need browser can show the page, There is also the thymeleaf can be very good and spring integration. Start learning below.
1. Introduction of dependency
Direct introduction of Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
You can view the dependencies and find that the spring-boot-starter-thymeleaf below already includes the Spring-boot-starter-web, so you can remove Spring-boot-starter-web dependencies.
2. Configure the View resolver
Spring-boot Many configurations have default configurations, such as the default page mapping path is
Classpath:/templates/*.html
The same static file path is
classpath:/static/
You can configure Thymeleaf template parser properties in application.properties. Just like the JSP parser configuration with SPRINGMVC
#thymeleaf startspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html#开发时关闭缓存,不然没法看到实时页面spring.thymeleaf.cache=false#thymeleaf end
The specific parameters can be configured to view
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
In this class, the above configuration is actually a property value injected into the class.
3. Write Demo
1. Controller
@Controller public class hellocontroller { private Logger Logger = Loggerfactory.getlogger (Hellocontroller.class); /** * Test Hello * @return */< /span> @RequestMapping (value = "/hello" , method = Requestmethod.get) public String hello (M Odel model) {Model.addattribute ( "name" , "Dear" ); return "hello" ; } }
2.view (annotated as idea-generated index for idea completion)
<! DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <title>Hello</title> <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 " /></head><body><!--/* @thymesVar id= "name" type= "java.lang.String" */--><p th:text="' hello! , ' + ${name} + '! ' >3333</P></body></html>
3. Effects
4. Basic syntax
Aftertaste above the demo, you can see the first to rewrite the HTML tag
In this way, you can use this syntax in other tags th:*
. This is the premise of the following syntax.
1. Get the value of a variable<p th:text="‘Hello!, ‘ + ${name} + ‘!‘" >3333</p>
It can be seen that getting the value of a variable &
is used as a symbol for JavaBean, 变量名.属性名
which is the same as an El expression.
In addition, the $
expression can only be written inside the th tag, otherwise it will not take effect, the above example is to use the value of the th:text
label to replace the p
value inside the label, as for the original value of P is only for the front-end development of the display used. This is good to do before and after the end of the separation.
2. Introduction of URLsThymeleaf for URL processing is through syntax @{...} To deal with.
<a th:href="@{http://blog.csdn.net/u012706811}">绝对路径</a><a th:href="@{/}">相对路径</a><a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>
Similar tags are: th:href
andth:src
3. String substitutionMost of the time, we just need to replace a place in a large paragraph of text, which can be done with a string concatenation operation:
<span th:text="‘Welcome to our application, ‘ + ${user.name} + ‘!‘">
A more concise approach is to:
<span th:text="|Welcome to our application, ${user.name}!|">
Of course, this form is more restrictive, |...| Can only contain variable expressions ${...}, cannot contain other constants, conditional expressions, and so on.
4. OperatorsYou can use various arithmetic operators in an expression, such as +,-, *,/,%
th:with="isEven=(${prodStat.count} % 2 == 0)"
logical operators, <, <=,>=,==,!= are all available, the only thing to note is the HTML escape character that needs to be used with <,>:
th:if="${prodStat.count} > 1" th:text="‘‘ + ( (${execMode} == ‘dev‘‘Development‘‘Production‘)"
5. ConditionsIf/unless
The thymeleaf uses the th:if and th:unless attributes for conditional judgment, and in the following example, the label is only displayed when the condition in the Th:if is true:
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
Th:unless is the opposite of th:if, the content is displayed only if the condition in the expression is not true.
Switch
Thymeleaf also supports multi-select switch structures:
<div th:switch="${user.role}"> <p th:case="‘admin‘"an administrator</p> <p th:case="#{roles.manager}"a manager</p></div>
Default property defaults can be represented by *:
<div th:switch="${user.role}"> <p th:case="' admin '">User is an administrator</P> <p th:case="#{roles.manager}">User is a manager</P> <p th:case="*">User is some other thing</P></div>
6. CycleRendering list data is a very common scenario, for example, there are now N records that need to be rendered as a table
, the data collection must be traversed, using the Th:each tag:
<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>
As you can see, you need to include the Th:each tag in the loop-rendered element (here), where th:each= "prod: ${prods}" means iterating over the set variable prods, which is prod in the loop body that can be accessed through an expression.
7.UtilitiesFor easier template use, Thymeleaf also provides a series of utility objects (built into the context) that can be accessed directly via #:
- #dates
- #calendars
- #numbers
- #strings
- Arrays
- Lists
- Sets
- Maps
- ...
Here is a snippet of code to illustrate some common methods:
Date
/* * FormatDate with theSpecified pattern * Also works witharrays, listsorSets */${#dates. Format (date, ' dd/mmm/yyyy hh:mm ')}${#dates. Arrayformat (Datesarray, ' dd/mmm/yyyy hh:mm ')}${#dates. ListFormat (dateslist, ' dd/mmm/yyyy hh:mm ')}${#dates. SetFormat (Datesset, ' dd/mmm/yyyy hh:mm ')}/* * Create ADate(java.util.Date) Object for the Current Date and Time*/${#dates. Createnow ()}/* * Create ADate(java.util.Date) Object for the Current Date( Time Set to xx:xx) */${#dates. Createtoday ()}
String
/* *CheckWhether aStringis empty (or null).performsA trim () operation before check *AlsoWorks with arrays, lists or sets */${#strings. IsEmpty (Name)}${#strings. Arrayisempty (Namearr)}${#strings. Listisempty (NameList)}${#strings. Setisempty (nameset)}/* *CheckWhether aStringStarts or ends with a fragment *AlsoWorks with arrays, lists or sets */${#strings. StartsWith (Name,' Don ')}//also array*, list* and set*${#strings. EndsWith (Name,endingfragment)}//also array*, list* and set*/* *ComputeLength *AlsoWorks with arrays, lists or sets */${#strings. Length (str)}/* *Null-safe comparison and concatenation * *${#strings. Equals (str)}${#strings. Equalsignorecase (str)}${#strings. Concat (str)}${#strings. Concatreplacenulls (str)}/* *Random*/${#strings. Randomalphanumeric (Count)}
Fast learning or directly write examples of the fastest, post-write demo encounter problems plus go
Reference Link: http://www.tianmaying.com/tutorial/using-thymeleaf
Spring Boot Learning Record (ii)--thymeleaf template