Spring Boot thymeleaf模板引擎的使用詳解
在早期開(kāi)發(fā)的時(shí)候,我們完成的都是靜態(tài)頁(yè)面也就是html頁(yè)面,隨著時(shí)間軸的發(fā)展,慢慢的引入了jsp頁(yè)面,當(dāng)在后端服務(wù)查詢(xún)到數(shù)據(jù)之后可以轉(zhuǎn)發(fā)到j(luò)sp頁(yè)面,可以輕松的使用jsp頁(yè)面來(lái)實(shí)現(xiàn)數(shù)據(jù)的顯示及交互,jsp有非常強(qiáng)大的功能,但是,在使用springboot的時(shí)候,整個(gè)項(xiàng)目是以jar包的方式運(yùn)行而不是war包,而且還嵌入了tomcat容器,因此,在默認(rèn)情況下是不支持jsp頁(yè)面的。如果直接以純靜態(tài)頁(yè)面的方式會(huì)給我們的開(kāi)發(fā)帶來(lái)很大的麻煩,springboot推薦使用模板引擎。
模板引擎有很多種,jsp,freemarker,thymeleaf,模板引擎的作用就是我們來(lái)寫(xiě)一個(gè)頁(yè)面模板,比如有些值呢,是動(dòng)態(tài)的,我們寫(xiě)一些表達(dá)式。而這些值,從哪來(lái)呢,我們來(lái)組裝一些數(shù)據(jù),我們把這些數(shù)據(jù)找到。然后把這個(gè)模板和這個(gè)數(shù)據(jù)交給我們模板引擎,模板引擎按照我們這個(gè)數(shù)據(jù)幫你把這表達(dá)式解析、填充到我們指定的位置,然后把這個(gè)數(shù)據(jù)最終生成一個(gè)我們想要的內(nèi)容給我們寫(xiě)出去,這就是我們這個(gè)模板引擎,不管是jsp還是其他模板引擎,都是這個(gè)思想。只不過(guò)不同的模板引擎語(yǔ)法不同而已,下面重點(diǎn)學(xué)習(xí)下springboot推薦使用的thymeleaf模板引擎,語(yǔ)法簡(jiǎn)單且功能強(qiáng)大
1、thymeleaf的介紹
官網(wǎng)地址:https://www.thymeleaf.org/
thymeleaf在github的地址:https://github.com/thymeleaf/thymeleaf
中文網(wǎng)站:https://raledong.gitbooks.io/using-thymeleaf/content/
導(dǎo)入依賴(lài):
<!--thymeleaf模板--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
在springboot中有專(zhuān)門(mén)的thymeleaf配置類(lèi):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代碼中寫(xiě)入如下代碼:
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","Hello");
//classpath:/templates/hello.html
return "hello";
}
html頁(yè)面中寫(xiě)入如下代碼:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Hello</h1>
<div th:text="${msg}"></div>
</body>
</html>
3、thymeleaf的表達(dá)式語(yǔ)法
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實(shí)例演示
1、th的常用屬性值
一、th:text :設(shè)置當(dāng)前元素的文本內(nèi)容,相同功能的還有th:utext,兩者的區(qū)別在于前者不會(huì)轉(zhuǎn)義html標(biāo)簽,后者會(huì)。優(yōu)先級(jí)不高:order=7
二、th:value:設(shè)置當(dāng)前元素的value值,類(lèi)似修改指定屬性的還有th:src,th:href。優(yōu)先級(jí)不高:order=6
三、th:each:遍歷循環(huán)元素,和th:text或th:value一起使用。注意該屬性修飾的標(biāo)簽位置,詳細(xì)往后看。優(yōu)先級(jí)很高:order=2
四、th:if:條件判斷,類(lèi)似的還有th:unless,th:switch,th:case。優(yōu)先級(jí)較高:order=3
五、th:insert:代碼塊引入,類(lèi)似的還有th:replace,th:include,三者的區(qū)別較大,若使用不恰當(dāng)會(huì)破壞html結(jié)構(gòu),常用于公共代碼塊提取的場(chǎng)景。優(yōu)先級(jí)最高:order=1
六、th:fragment:定義代碼塊,方便被th:insert引用。優(yōu)先級(jí)最低:order=8
七、th:object:聲明變量,一般和*{}一起配合使用,達(dá)到偷懶的效果。優(yōu)先級(jí)一般:order=4
八、th:attr:修改任意屬性,實(shí)際開(kāi)發(fā)中用的較少,因?yàn)橛胸S富的其他th屬性幫忙,類(lèi)似的還有th:attrappend,th:attrprepend。優(yōu)先級(jí)一般: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設(shè)置文本內(nèi)容 <b>加粗</b>");
map.put("thUText","th:utext 設(shè)置文本內(nèi)容 <b>加粗</b>");
map.put("thValue","thValue 設(shè)置當(dāng)前元素的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、標(biāo)準(zhǔn)表達(dá)式語(yǔ)法
${...} 變量表達(dá)式,Variable Expressions
*{...} 選擇變量表達(dá)式,Selection Variable Expressions
一、可以獲取對(duì)象的屬性和方法
二、可以使用ctx,vars,locale,request,response,session,servletContext內(nèi)置對(duì)象
session.setAttribute("user","zhangsan");
th:text="${session.user}"
三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等內(nèi)置方法
standardExpression.html
<!--
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
二、numbers:數(shù)值格式化方法,常用的方法有:formatDecimal等
三、bools:布爾方法,常用的方法有:isTrue,isFalse等
四、arrays:數(shù)組方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:對(duì)象方法,常用的方法有: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內(nèi)置方法</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 整數(shù)部分隨意,小數(shù)點(diǎn)后保留兩位,四舍五入: <span th:text="${#numbers.formatDecimal(Num, 0, 2)}"/></p>
<p>formatDecimal 整數(shù)部分保留五位數(shù),小數(shù)點(diǎn)后保留兩位,四舍五入: <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", "變量表達(dá)式內(nèi)置方法");
map.put("Map", hashMap);
map.put("Date", new Date());
map.put("Num", 888.888D);
return "standardExpression";
}
@{...} 鏈接表達(dá)式,Link URL Expressions
<!--
不管是靜態(tài)資源的引用,form表單的請(qǐng)求,凡是鏈接都可以用@{...} 。這樣可以動(dòng)態(tài)獲取項(xiàng)目路徑,即便項(xiàng)目名變了,依然可以正常訪問(wèn)
鏈接表達(dá)式結(jié)構(gòu)
無(wú)參:@{/xxx}
有參:@{/xxx(k1=v1,k2=v2)} 對(duì)應(yīng)url結(jié)構(gòu):xxx?k1=v1&k2=v2
引入本地資源:@{/項(xiàng)目本地的資源路徑}
引入外部資源:@{/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>
#{...} 消息表達(dá)式,Message Expressions
<!--
消息表達(dá)式一般用于國(guó)際化的場(chǎng)景。結(jié)構(gòu):th:text="#{msg}"
-->
~{...} 代碼塊表達(dá)式,F(xiàn)ragment Expressions
fragment.html
<!--
支持兩種語(yǔ)法結(jié)構(gòu)
推薦:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf會(huì)根據(jù)模版名解析完整路:/resources/templates/templatename.html,要注意文件的路徑。
fragmentname:片段名,Thymeleaf通過(guò)th:fragment聲明定義代碼塊,即:th:fragment="fragmentname"
id:HTML的id選擇器,使用時(shí)要在前面加上#號(hào),不支持class選擇器。
代碼塊表達(dá)式的使用
代碼塊表達(dá)式需要配合th屬性(th:insert,th:replace,th:include)一起使用。
th:insert:將代碼塊片段整個(gè)插入到使用了th:insert的HTML標(biāo)簽中,
th:replace:將代碼塊片段整個(gè)替換使用了th:replace的HTML標(biāo)簽中,
th:include:將代碼塊片段包含的內(nèi)容插入到使用了th:include的HTML標(biāo)簽中,
-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:fragment定義代碼塊標(biāo)識(shí)-->
<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是將代碼塊代替當(dāng)前div,其html結(jié)構(gòu)和之前一致-->
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<!--th:include是將代碼塊footer的內(nèi)容插入到div中,即少了一層footer-->
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>
5、國(guó)際化的配置
在很多應(yīng)用場(chǎng)景下,我們需要實(shí)現(xiàn)頁(yè)面的國(guó)際化,springboot對(duì)國(guó)際化有很好的支持, 下面來(lái)演示對(duì)應(yīng)的效果。
1、在idea中設(shè)置統(tǒng)一的編碼格式,file->settings->Editors->File Encoding,選擇編碼格式為utf-8
2、在resources資源文件下創(chuàng)建一個(gè)i8n的目錄,創(chuàng)建一個(gè)login.properties的文件,還有l(wèi)ogin_zh_CN.properties,idea會(huì)自動(dòng)識(shí)別國(guó)際化操作
3、創(chuàng)建三個(gè)不同的文件,名稱(chēng)分別是:login.properties,login_en_US.properties,login_zh_CN.properties
內(nèi)容如下:
#login.properties login.password=密碼1 login.remmber=記住我1 login.sign=登錄1 login.username=用戶(hù)名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=用戶(hù)名~
4、配置國(guó)際化的資源路徑
spring: messages: basename: i18n/login
5、編寫(xiě)html頁(yè)面
初始html頁(yè)面
<!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>
修改后的頁(yè)面
<!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>
可以看到通過(guò)瀏覽器的切換語(yǔ)言已經(jīng)能夠?qū)崿F(xiàn),想要通過(guò)超鏈接實(shí)現(xiàn)的話,如下所示:
添加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頁(yè)面修改為:
<!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>
國(guó)際化的源碼解釋?zhuān)?/p>
//MessageSourceAutoConfiguration
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = new Resource[0];
public MessageSourceAutoConfiguration() {
}
@Bean
@ConfigurationProperties(prefix = "spring.messages") //我們的配置文件可以直接放在類(lèi)路徑下叫: messages.properties, 就可以進(jìn)行國(guó)際化操作了
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
//設(shè)置國(guó)際化文件的基礎(chǔ)名(去掉語(yǔ)言國(guó)家代碼的)
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);
}
到此這篇關(guān)于Spring Boot thymeleaf模板引擎的使用詳解的文章就介紹到這了,更多相關(guān)Spring Boot thymeleaf模板引擎內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot整合redisson實(shí)現(xiàn)延時(shí)隊(duì)列(附倉(cāng)庫(kù)地址)
延時(shí)隊(duì)列用于管理需要定時(shí)執(zhí)行的任務(wù),對(duì)于大數(shù)據(jù)量和高實(shí)時(shí)性需求,使用延時(shí)隊(duì)列比定時(shí)掃庫(kù)更高效,Redisson提供一種高效的延時(shí)隊(duì)列實(shí)現(xiàn)方式,本文就來(lái)詳細(xì)的介紹一下,感興趣都可以了解學(xué)習(xí)2024-10-10
極簡(jiǎn)的Resty服務(wù)端和客戶(hù)端RESTful框架
這篇文章主要為大家介紹了極簡(jiǎn)的Resty服務(wù)端和客戶(hù)端RESTful框架的好處及作用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
Java中日期時(shí)間比較的多種方法及實(shí)用代碼
本文介紹了Java中不同日期時(shí)間類(lèi)的比較方法,包括java.util.Date、java.util.Calendar、java.time?API和java.sql.Timestamp,提供了使用before、after和compareTo等方法進(jìn)行日期比較的示例代碼,展示了各自的特點(diǎn)和使用場(chǎng)景,需要的朋友可以參考下2024-09-09
Java學(xué)習(xí)之反射機(jī)制及應(yīng)用場(chǎng)景介紹
本篇文章主要介紹了Java反射機(jī)制及應(yīng)用場(chǎng)景,反射機(jī)制是很多Java框架的基石。非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2016-11-11
mybatis水平分表實(shí)現(xiàn)動(dòng)態(tài)表名的項(xiàng)目實(shí)例
本文主要介紹了mybatis水平分表實(shí)現(xiàn)動(dòng)態(tài)表名的項(xiàng)目實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
logback.xml動(dòng)態(tài)配置程序路徑的操作
這篇文章主要介紹了logback.xml動(dòng)態(tài)配置程序路徑的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Java開(kāi)發(fā)之spring security實(shí)現(xiàn)基于MongoDB的認(rèn)證功能
這篇文章主要介紹了Java開(kāi)發(fā)之spring security實(shí)現(xiàn)基于MongoDB的認(rèn)證功能,結(jié)合實(shí)例形式分析了spring security在非JDBC環(huán)境下的自定義認(rèn)證服務(wù)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-11-11
Spring加載屬性文件方式(自動(dòng)加載優(yōu)先級(jí)問(wèn)題)
這篇文章主要介紹了Spring加載屬性文件方式(自動(dòng)加載優(yōu)先級(jí)問(wèn)題),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

