Spring Boot application enables an ability of switching multilingualism.
- Import dependencies
<dependency>
<groupId>com.yookue.springstarter</groupId>
<artifactId>locale-change-spring-boot-starter</artifactId>
<version>LATEST</version>
</dependency>
By default, this starter will auto take effect, you can turn it off by
spring.locale-change.enabled = false
- Configure Spring Boot
application.yml
with prefixspring.locale-change
spring:
locale-change:
model-and-view:
view-attribute: 'localeChangeTagNames'
tag-multilingual: false
tag-names:
'en-US': 'English'
'zh-CN': '简体中文'
'zh-TW': '繁体中文'
locale-interceptor:
param-name: 'lang'
intercept-paths:
- '/**'
exclude-paths:
- '/foo/**'
- '/bar/**'
cookie-locale-resolver:
http-only: true
-
Optional feature: If you want to display the
tag-names
value in multilingual (not the fixed value inapplication.properties
), for example, display the value ofzh-CN
to简体中文
when current request is usingzh
locale, or displaySimplified Chinese
when the request is usingen
locale. You can reach your goal as following:- Configure the
tag-multilingual
attribute totrue
- Set the value of
zh-CN
tolocale-change.dropdown-switch
- Write the
locale-change.dropdown-switch
as a key in a resource bundle properties that could be loaded by the primaryMessageSource
bean (Just as our another Spring startermessage-source-spring-boot-starter
does)
- Configure the
-
Write your template code as following (take
Thymeleaf
as an example)
Under the head
segment (optional):
<meta name="language-raw" th:content="${#locale.toLanguageTag()}" th:if="${not #localeChange.contains(#locale)}"/>
<meta name="language-tag" th:content="${#localeChange.contains(#locale) ? #locale.toLanguageTag() : 'en-US'}"/>
Under the body
segment:
<ul>
<li class="lang-switch dropdown">
<a href="javascript:">
<i class="fa fa-globe" aria-hidden="true"></i>
<span>Language</span>
<i class="bi bi-chevron-down"></i>
</a>
<ul role="menu" th:if="${not #maps.isEmpty(localeChangeTagNames)}">
<li th:each="tagName: ${localeChangeTagNames}"><a th:href="${'?lang=' + tagName.key}"><span th:text="${tagName.value}">Placeholder</span></a></li>
</ul>
</li>
</ul>
- jdk 17+
This project is under the Apache License 2.0
See the NOTICE.txt
file for required notices and attributions.
You like this package? Then donate to Yookue to support the development.
- Yookue: https://yookue.com