如何在Spring Boot + Thymeleaf中配置国际化并实现多语言显示?
Hey there! Let's break down how to implement multi-language text translation based on user locale in a Spring Boot project with Thymeleaf, plus how to display those localized messages in your templates.
First, you need to set up property files that hold your translated text. These go in the src/main/resources directory of your project.
- The default fallback file:
messages.properties(use this for your base language, e.g., English) - Language-specific files: Name them using the pattern
messages_{locale}.properties, like:messages_en.properties(English)messages_zh_CN.properties(Simplified Chinese)messages_fr.properties(French)
Example content for each file:
messages.properties:greeting=Hello! welcome.message=Welcome, {0}! input.username=Enter your usernamemessages_zh_CN.properties:greeting=你好! welcome.message=欢迎你,{0}! input.username=请输入用户名messages_fr.properties:greeting=Bonjour ! welcome.message=Bienvenue, {0} ! input.username=Entrez votre nom d'utilisateur
Next, you need to tell Spring how to handle locale resolution and allow users to switch languages. Create a configuration class that implements WebMvcConfigurer:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import java.util.Locale; @Configuration public class WebI18nConfig implements WebMvcConfigurer { // Define how locale is stored (here, using a cookie to persist across sessions) @Bean public LocaleResolver localeResolver() { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setDefaultLocale(Locale.ENGLISH); // Fallback locale resolver.setCookieName("user-lang"); // Name of the cookie to store locale resolver.setCookieMaxAge(86400); // Keep cookie for 1 day return resolver; } // Allow switching locale via a request parameter (e.g., ?lang=zh_CN) @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); interceptor.setParamName("lang"); // The request parameter name return interceptor; } // Register the interceptor so Spring uses it @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
You can also use SessionLocaleResolver instead of CookieLocaleResolver if you don't want to persist the locale across browser sessions.
Thymeleaf makes it super easy to reference your message keys using the #{key} syntax. Here are common use cases:
Basic Message Display
<!-- Show the greeting message --> <h1 th:text="#{greeting}"></h1>
Messages with Parameters
If your message has placeholders (like {0} in the example), pass variables using parentheses:
<!-- Assume ${username} is a variable from your controller --> <p th:text="#{welcome.message(${username})}"></p>
Form Placeholders/Labels
<label th:text="#{input.username}"></label> <input type="text" th:placeholder="#{input.username}" />
Use in JavaScript
If you need localized text in JS, use Thymeleaf's inline scripting:
<script th:inline="javascript"> const greeting = [[#{greeting}]]; alert(greeting); </script>
Show Current Locale
You can also display the active locale's details:
<p>Current language: <span th:text="${#locale.language}"></span></p> <p>Display name: <span th:text="${#locale.displayName}"></span></p>
Let users switch languages with simple links. Use Thymeleaf's URL expression @{} to preserve existing request parameters while adding the lang parameter:
<div class="language-switcher"> <a th:href="@{/(lang='en')}">English</a> <a th:href="@{/(lang='zh_CN')}">中文</a> <a th:href="@{/(lang='fr')}">Français</a> </div>
When a user clicks one of these links, the LocaleChangeInterceptor will update the active locale.
If a message key isn't found in the active locale's property file, Spring will automatically fall back to:
- The locale's parent language (e.g.,
zhifzh_CNdoesn't have the key) - Finally, the default
messages.propertiesfile
So make sure your default file includes all essential keys to avoid missing text.
内容的提问来源于stack exchange,提问作者the duck wizard

