Spring Boot thymeleaf模板引擎的使用详解
在早期开发的时候,我们完成的都是静态页面也就是html页面,随着时间轴的发展,慢慢的引入了jsp页面,当在后端服务查询到数据之后可以转发到jsp页面,可以轻松的使用jsp页面来实现数据的显示及交互,jsp有非常强大的功能,但是,在使用springboot的时候,整个项目是以jar包的方式运行而不是war包,而且还嵌入了tomcat容器,因此,在默认情况下是不支持jsp页面的。如果直接以纯静态页面的方式会给我们的开发带来很大的麻烦,springboot推荐使用模板引擎。
模板引擎有很多种,jsp,freemarker,thymeleaf,模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,我们来组装一些数据,我们把这些数据找到。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过不同的模板引擎语法不同而已,下面重点学习下springboot推荐使用的thymeleaf模板引擎,语法简单且功能强大
1、thymeleaf的介绍
官网地址:
thymeleaf在github的地址:
中文网站:
导入依赖:
<!--thymeleaf模板--> <dependency> <groupid>org.thymeleaf</groupid> <artifactid>thymeleaf-spring5</artifactid> </dependency> <dependency> <groupid>org.thymeleaf.extras</groupid> <artifactid>thymeleaf-extras-java8time</artifactid> </dependency>
在springboot中有专门的thymeleaf配置类:thymeleafproperties
@configurationproperties(prefix = "spring.thymeleaf") public class thymeleafproperties { private static final charset default_encoding = standardcharsets.utf_8; public static final string default_prefix = "classpath:/templates/"; public static final string default_suffix = ".html"; /** * whether to check that the template exists before rendering it. */ private boolean checktemplate = true; /** * whether to check that the templates location exists. */ private boolean checktemplatelocation = true; /** * prefix that gets prepended to view names when building a url. */ private string prefix = default_prefix; /** * suffix that gets appended to view names when building a url. */ private string suffix = default_suffix; /** * template mode to be applied to templates. see also thymeleaf's templatemode enum. */ private string mode = "html"; /** * template files encoding. */ private charset encoding = default_encoding; /** * whether to enable template caching. */ private boolean cache = true;
2、thymeleaf使用模板
在java代码中写入如下代码:
@requestmapping("/hello") public string hello(model model){ model.addattribute("msg","hello"); //classpath:/templates/hello.html return "hello"; }
html页面中写入如下代码:
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <body> <h1>hello</h1> <div th:text="${msg}"></div> </body> </html>
3、thymeleaf的表达式语法
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: _
4、thymeleaf实例演示
1、th的常用属性值
一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5
thymeleaf.html
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <p th:text="${thtext}"></p> <p th:utext="${thutext}"></p> <input type="text" th:value="${thvalue}"> <div th:each="message:${theach}"> <p th:text="${message}"></p> </div> <div> <p th:text="${message}" th:each="message:${theach}"></p> </div> <p th:text="${thif}" th:if="${not #strings.isempty(thif)}"></p> <div th:object="${thobject}"> <p>name:<span th:text="*{name}"/></p> <p>age:<span th:text="*{age}"/></p> <p>gender:<span th:text="*{gender}"/></p> </div> </body> </html>
thymeleafcontroller.java
import org.springframework.stereotype.controller; import org.springframework.ui.modelmap; import org.springframework.web.bind.annotation.requestmapping; @controller public class thymeleafcontroller { @requestmapping("thymeleaf") public string thymeleaf(modelmap map){ map.put("thtext","th:text设置文本内容 <b>加粗</b>"); map.put("thutext","th:utext 设置文本内容 <b>加粗</b>"); map.put("thvalue","thvalue 设置当前元素的value值"); map.put("theach","arrays.aslist(\"th:each\", \"遍历列表\")"); map.put("thif","msg is not null"); map.put("thobject",new person("zhangsan",12,"男")); return "thymeleaf"; } }
2、标准表达式语法
${...} 变量表达式,variable expressions
*{...} 选择变量表达式,selection variable expressions
一、可以获取对象的属性和方法
二、可以使用ctx,vars,locale,request,response,session,servletcontext内置对象
session.setattribute("user","zhangsan"); th:text="${session.user}"
三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法
standardexpression.html
<!-- 一、strings:字符串格式化方法,常用的java方法它都有。比如:equals,equalsignorecase,length,trim,touppercase,tolowercase,indexof,substring,replace,startswith,endswith,contains,containsignorecase等 二、numbers:数值格式化方法,常用的方法有:formatdecimal等 三、bools:布尔方法,常用的方法有:istrue,isfalse等 四、arrays:数组方法,常用的方法有:toarray,length,isempty,contains,containsall等 五、lists,sets:集合方法,常用的方法有:tolist,size,isempty,contains,containsall,sort等 六、maps:对象方法,常用的方法有:size,isempty,containskey,containsvalue等 七、dates:日期方法,常用的方法有:format,year,month,hour,createnow等 --> <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>thymeleaf内置方法</title> </head> <body> <h3>#strings </h3> <div th:if="${not #strings.isempty(str)}" > <p>old str : <span th:text="${str}"/></p> <p>touppercase : <span th:text="${#strings.touppercase(str)}"/></p> <p>tolowercase : <span th:text="${#strings.tolowercase(str)}"/></p> <p>equals : <span th:text="${#strings.equals(str, 'blog')}"/></p> <p>equalsignorecase : <span th:text="${#strings.equalsignorecase(str, 'blog')}"/></p> <p>indexof : <span th:text="${#strings.indexof(str, 'r')}"/></p> <p>substring : <span th:text="${#strings.substring(str, 2, 4)}"/></p> <p>replace : <span th:text="${#strings.replace(str, 'it', 'it')}"/></p> <p>startswith : <span th:text="${#strings.startswith(str, 'it')}"/></p> <p>contains : <span th:text="${#strings.contains(str, 'it')}"/></p> </div> <h3>#numbers </h3> <div> <p>formatdecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatdecimal(num, 0, 2)}"/></p> <p>formatdecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatdecimal(num, 5, 2)}"/></p> </div> <h3>#bools </h3> <div th:if="${#bools.istrue(bool)}"> <p th:text="${bool}"></p> </div> <h3>#arrays </h3> <div th:if="${not #arrays.isempty(array)}"> <p>length : <span th:text="${#arrays.length(array)}"/></p> <p>contains : <span th:text="${#arrays.contains(array,2)}"/></p> <p>containsall : <span th:text="${#arrays.containsall(array, array)}"/></p> </div> <h3>#lists </h3> <div th:if="${not #lists.isempty(list)}"> <p>size : <span th:text="${#lists.size(list)}"/></p> <p>contains : <span th:text="${#lists.contains(list, 0)}"/></p> <p>sort : <span th:text="${#lists.sort(list)}"/></p> </div> <h3>#maps </h3> <div th:if="${not #maps.isempty(hashmap)}"> <p>size : <span th:text="${#maps.size(hashmap)}"/></p> <p>containskey : <span th:text="${#maps.containskey(hashmap, 'thname')}"/></p> <p>containsvalue : <span th:text="${#maps.containsvalue(hashmap, '#maps')}"/></p> </div> <h3>#dates </h3> <div> <p>format : <span th:text="${#dates.format(date)}"/></p> <p>custom format : <span th:text="${#dates.format(date, 'yyyy-mm-dd hh:mm:ss')}"/></p> <p>day : <span th:text="${#dates.day(date)}"/></p> <p>month : <span th:text="${#dates.month(date)}"/></p> <p>monthname : <span th:text="${#dates.monthname(date)}"/></p> <p>year : <span th:text="${#dates.year(date)}"/></p> <p>dayofweekname : <span th:text="${#dates.dayofweekname(date)}"/></p> <p>hour : <span th:text="${#dates.hour(date)}"/></p> <p>minute : <span th:text="${#dates.minute(date)}"/></p> <p>second : <span th:text="${#dates.second(date)}"/></p> <p>createnow : <span th:text="${#dates.createnow()}"/></p> </div> </body> </html>
thymeleafcontroller.java
@requestmapping("standardexpression") public string standardexpression(modelmap map){ map.put("str", "blog"); map.put("bool", true); map.put("array", new integer[]{1,2,3,4}); map.put("list", arrays.aslist(1,3,2,4,0)); map hashmap = new hashmap(); hashmap.put("thname", "${#...}"); hashmap.put("desc", "变量表达式内置方法"); map.put("map", hashmap); map.put("date", new date()); map.put("num", 888.888d); return "standardexpression"; }
@{...} 链接表达式,link url expressions
<!-- 不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问 链接表达式结构 无参:@{/xxx} 有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2 引入本地资源:@{/项目本地的资源路径} 引入外部资源:@{/webjars/资源在jar包中的路径} --> <link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="external nofollow" rel="stylesheet"> <link th:href="@{/main/css/123.css}" rel="external nofollow" rel="stylesheet"> <form class="form-login" th:action="@{/user/login}" th:method="post" > <a class="btn btn-sm" th:href="@{/login.html(l='zh_cn')}" rel="external nofollow" >中文</a> <a class="btn btn-sm" th:href="@{/login.html(l='en_us')}" rel="external nofollow" >english</a>
#{...} 消息表达式,message expressions
<!-- 消息表达式一般用于国际化的场景。结构:th:text="#{msg}" -->
~{...} 代码块表达式,fragment expressions
fragment.html
<!-- 支持两种语法结构 推荐:~{templatename::fragmentname} 支持:~{templatename::#id} templatename:模版名,thymeleaf会根据模版名解析完整路:/resources/templates/templatename.html,要注意文件的路径。 fragmentname:片段名,thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname" id:html的id选择器,使用时要在前面加上#号,不支持class选择器。 代码块表达式的使用 代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。 th:insert:将代码块片段整个插入到使用了th:insert的html标签中, th:replace:将代码块片段整个替换使用了th:replace的html标签中, th:include:将代码块片段包含的内容插入到使用了th:include的html标签中, --> <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <!--th:fragment定义代码块标识--> <footer th:fragment="copy"> 2019 the good thymes virtual grocery </footer> <!--三种不同的引入方式--> <div th:insert="fragment::copy"></div> <div th:replace="fragment::copy"></div> <div th:include="fragment::copy"></div> <!--th:insert是在div中插入代码块,即多了一层div--> <div> <footer> © 2011 the good thymes virtual grocery </footer> </div> <!--th:replace是将代码块代替当前div,其html结构和之前一致--> <footer> © 2011 the good thymes virtual grocery </footer> <!--th:include是将代码块footer的内容插入到div中,即少了一层footer--> <div> © 2011 the good thymes virtual grocery </div> </body> </html>
5、国际化的配置
在很多应用场景下,我们需要实现页面的国际化,springboot对国际化有很好的支持, 下面来演示对应的效果。
1、在idea中设置统一的编码格式,file->settings->editors->file encoding,选择编码格式为utf-8
2、在resources资源文件下创建一个i8n的目录,创建一个login.properties的文件,还有login_zh_cn.properties,idea会自动识别国际化操作
3、创建三个不同的文件,名称分别是:login.properties,login_en_us.properties,login_zh_cn.properties
内容如下:
#login.properties login.password=密码1 login.remmber=记住我1 login.sign=登录1 login.username=用户名1 #login_en_us.properties login.password=password login.remmber=remember me login.sign=sign in login.username=username #login_zh_cn.properties login.password=密码~ login.remmber=记住我~ login.sign=登录~ login.username=用户名~
4、配置国际化的资源路径
spring: messages: basename: i18n/login
5、编写html页面
初始html页面 <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <title>title</title> </head> <body> <form action="" method="post"> <label >username</label> <input type="text" name="username" placeholder="username" > <label >password</label> <input type="password" name="password" placeholder="password" > <br> <br> <div> <label> <input type="checkbox" value="remember-me"/> remember me </label> </div> <br> <button type="submit">sign in</button> <br> <br> <a>中文</a> <a>english</a> </form> </body> </html> 修改后的页面 <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <title>title</title> </head> <body> <form action="" method="post"> <label th:text="#{login.username}">username</label> <input type="text" name="username" placeholder="username" th:placeholder="#{login.username}"> <label th:text="#{login.password}">password</label> <input type="password" name="password" placeholder="password" th:placeholder="#{login.password}"> <br> <br> <div> <label> <input type="checkbox" value="remember-me"/> [[#{login.remmber}]] </label> </div> <br> <button type="submit" th:text="#{login.sign}">sign in</button> <br> <br> <a>中文</a> <a>english</a> </form> </body> </html>
可以看到通过浏览器的切换语言已经能够实现,想要通过超链接实现的话,如下所示:
添加webmvcconfig.java代码
import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.util.stringutils; import org.springframework.web.servlet.localeresolver; import org.springframework.web.servlet.config.annotation.viewcontrollerregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigurer; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.util.locale; @configuration public class webmvcconfig implements webmvcconfigurer { @override public void addviewcontrollers(viewcontrollerregistry registry) { registry.addviewcontroller("/").setviewname("login"); registry.addviewcontroller("/login.html").setviewname("login"); } @bean public localeresolver localeresolver(){ return new nativelocaleresolver(); } protected static class nativelocaleresolver implements localeresolver{ @override public locale resolvelocale(httpservletrequest request) { string language = request.getparameter("language"); locale locale = locale.getdefault(); if(!stringutils.isempty(language)){ string[] split = language.split("_"); locale = new locale(split[0],split[1]); } return locale; } @override public void setlocale(httpservletrequest request, httpservletresponse response, locale locale) { } } }
login.html页面修改为:
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <title>title</title> </head> <body> <form action="" method="post"> <label th:text="#{login.username}">username</label> <input type="text" name="username" placeholder="username" th:placeholder="#{login.username}"> <label th:text="#{login.password}">password</label> <input type="password" name="password" placeholder="password" th:placeholder="#{login.password}"> <br> <br> <div> <label> <input type="checkbox" value="remember-me"/> [[#{login.remmber}]] </label> </div> <br> <button type="submit" th:text="#{login.sign}">sign in</button> <br> <br> <a th:href="@{/login.html(language='zh_cn')}" rel="external nofollow" >中文</a> <a th:href="@{/login.html(language='en_us')}" rel="external nofollow" >english</a> </form> </body> </html>
国际化的源码解释:
//messagesourceautoconfiguration public class messagesourceautoconfiguration { private static final resource[] no_resources = new resource[0]; public messagesourceautoconfiguration() { } @bean @configurationproperties(prefix = "spring.messages") //我们的配置文件可以直接放在类路径下叫: messages.properties, 就可以进行国际化操作了 public messagesourceproperties messagesourceproperties() { return new messagesourceproperties(); } @bean public messagesource messagesource(messagesourceproperties properties) { resourcebundlemessagesource messagesource = new resourcebundlemessagesource(); if (stringutils.hastext(properties.getbasename())) { //设置国际化文件的基础名(去掉语言国家代码的) messagesource.setbasenames(stringutils.commadelimitedlisttostringarray(stringutils.trimallwhitespace(properties.getbasename()))); } if (properties.getencoding() != null) { messagesource.setdefaultencoding(properties.getencoding().name()); } messagesource.setfallbacktosystemlocale(properties.isfallbacktosystemlocale()); duration cacheduration = properties.getcacheduration(); if (cacheduration != null) { messagesource.setcachemillis(cacheduration.tomillis()); } messagesource.setalwaysusemessageformat(properties.isalwaysusemessageformat()); messagesource.setusecodeasdefaultmessage(properties.isusecodeasdefaultmessage()); return messagesource; } } //webmvcautoconfiguration @bean @conditionalonmissingbean @conditionalonproperty(prefix = "spring.mvc", name = "locale") public localeresolver localeresolver() { if (this.mvcproperties.getlocaleresolver() == webmvcproperties.localeresolver.fixed) { return new fixedlocaleresolver(this.mvcproperties.getlocale()); } acceptheaderlocaleresolver localeresolver = new acceptheaderlocaleresolver(); localeresolver.setdefaultlocale(this.mvcproperties.getlocale()); return localeresolver; } //acceptheaderlocaleresolver @override public locale resolvelocale(httpservletrequest request) { locale defaultlocale = getdefaultlocale(); if (defaultlocale != null && request.getheader("accept-language") == null) { return defaultlocale; } locale requestlocale = request.getlocale(); list<locale> supportedlocales = getsupportedlocales(); if (supportedlocales.isempty() || supportedlocales.contains(requestlocale)) { return requestlocale; } locale supportedlocale = findsupportedlocale(request, supportedlocales); if (supportedlocale != null) { return supportedlocale; } return (defaultlocale != null ? defaultlocale : requestlocale); }
到此这篇关于spring boot thymeleaf模板引擎的使用详解的文章就介绍到这了,更多相关spring boot thymeleaf模板引擎内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
spring boot使用properties定义短信模板的方法教程
-
spring boot使用thymeleaf为模板的基本步骤介绍
-
使用dubbo+zookeeper+spring boot构建服务的方法详解
-
Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图的方法
-
spring boot Logging的配置以及使用详解
-
Spring boot中PropertySource注解的使用方法详解
-
详解Spring Boot配置使用Logback进行日志记录的实战
-
详解Spring Boot下Druid连接池的使用配置分析
-
spring boot使用thymeleaf模板的方法详解
-
详解Spring Boot中MyBatis的使用方法