You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

1. Create Message Resource Files

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 username
    
  • messages_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
    
2. Configure Spring Boot for I18n

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.

3. Display Localized Messages in Thymeleaf

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>
4. Add a Language Switcher

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.

5. Fallback Behavior

If a message key isn't found in the active locale's property file, Spring will automatically fall back to:

  1. The locale's parent language (e.g., zh if zh_CN doesn't have the key)
  2. Finally, the default messages.properties file

So make sure your default file includes all essential keys to avoid missing text.

内容的提问来源于stack exchange,提问作者the duck wizard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:39:16