SpringBoot实现国际化i18n详解

 更新时间:2024年12月15日 08:14:04   作者:HBLOG  
国际化(Internationalization,简称i18n)是指在软件应用中支持多种语言和文化的能力,本文将介绍如何在Spring Boot应用中实现国际化,需要的可以参考下

1.什么是国际化(i18n)

国际化(Internationalization,简称i18n)是指在软件应用中支持多种语言和文化的能力。通过国际化,应用可以根据用户的语言和地区设置,动态地显示不同的文本内容。本文将介绍如何在Spring Boot应用中实现国际化,并提供完整的代码示例。

2.代码工程

在Spring Boot中实现国际化(i18n)可以通过以下步骤完成。我们将使用Spring的消息源(MessageSource)功能来支持多语言文本。

步骤 1: 创建项目

首先,创建一个新的Spring Boot项目。可以使用Spring Initializr(start.spring.io/)来生成项目,选择以下…

Spring Web

Spring Boot DevTools(可选,用于热重载)

springboot-demo com.et 1.0-SNAPSHOT 4.0.0

<artifactId>i18n</artifactId>

<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

步骤 2: 创建国际化资源文件

src/main/resources目录下,创建一个名为messages的文件夹,并在其中创建不同语言的资源文件。例如:

  • messages.properties(默认语言,通常是英语)
  • messages_zh.properties(中文)
  • messages_fr.properties(法语)

每个文件的内容如下:

messages.properties(默认语言)

greeting=Hello!
farewell=Goodbye!

messages_zh.properties(中文)

greeting=你好!
farewell=再见!

messages_fr.properties(法语)

greeting=Bonjour!
farewell=Au revoir!

步骤 3: 配置MessageSource

在Spring Boot中,默认会自动配置MessageSource,但你可以自定义配置。创建一个配置类,例如MessageConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@Configuration
public class MessageConfig {

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

步骤 4: 创建Controller

创建一个控制器来处理请求并返回国际化的消息:

package com.et.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@RestController
public class GreetingController {

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private LocaleResolver localeResolver;

    @GetMapping("/greeting")
    public String greeting(HttpServletRequest request, @RequestHeader(value = "Accept-Language", required = false) String acceptLanguage) {
        Locale locale = localeResolver.resolveLocale(request);
        
        // set language by Accept-Language
        if (acceptLanguage != null && !acceptLanguage.isEmpty()) {
            String[] languages = acceptLanguage.split(",");
            String language = languages[0].split(";")[0]; // get the first language
            language = language.trim();
            locale = Locale.forLanguageTag(language);
        }

        return messageSource.getMessage("greeting", null, locale);
    }
}

步骤 5: 前端实现

如果你有前端页面,可以通过AJAX请求获取国际化文本。例如,使用JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internationalization Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            color: #333;
            padding: 20px;
        }
        select {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<h1 id="greeting"></h1>

<label for="language-select">Choose a language:</label>
<select id="language-select">
    <option value="en">English</option>
    <option value="zh">中文</option>
    <option value="fr">Français</option>
</select>

<script>
        function fetchGreeting(lang) {
            fetch('/greeting', {
                method: 'GET',
                headers: {
                    'Accept-Language': lang
                }
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('greeting').innerText = data;
            });


        }

        // Fetch greeting based on selected language
        document.getElementById('language-select').addEventListener('change', function() {
            const selectedLang = this.value;
            fetchGreeting(selectedLang);
        });

        // Initial fetch in English
        fetchGreeting('en');
    </script>
</body>
</html>

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

github.com/Harries/springboot-demo(i18n)

3.测试

启动Spring Boot应用,访问http://127.0.0.1:8088/index.html。效果如下图

4.总结

通过以上步骤,你可以在Spring Boot应用中实现国际化。你可以根据用户的语言偏好动态地返回不同的文本内容。根据需要,你可以扩展更多语言和消息,并在前端实现语言切换功能。

到此这篇关于SpringBoot实现国际化i18n详解的文章就介绍到这了,更多相关SpringBoot国际化i18n内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • jfinal添加jcaptcha验证码实现方法

    jfinal添加jcaptcha验证码实现方法

    这篇文章主要介绍了jfinal的jcaptcha验证码实现方法,大家参考使用吧
    2014-01-01
  • java实现时间控制的几种方案

    java实现时间控制的几种方案

    这篇文章主要介绍了java实现时间控制的几种方案,本文从多个方面给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-07-07
  • Spring中ApplicationContext的拓展功能详解

    Spring中ApplicationContext的拓展功能详解

    这篇文章主要介绍了Spring中ApplicationContext的拓展功能详解,相对于BeanFactory来说,ApplicationContext除了提供BeanFactory的所有功能外,还有一些其他的功能,主要包括国际化支持、资源访问、事件传递,需要的朋友可以参考下
    2024-01-01
  • java判定数组或集合是否存在某个元素的实例

    java判定数组或集合是否存在某个元素的实例

    下面小编就为大家带来一篇java判定数组或集合是否存在某个元素的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • Java10新特性解读

    Java10新特性解读

    这篇文章主要介绍了Java10新特性的相关资料,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2021-02-02
  • Java使用connectTo方法提高代码可续性详解

    Java使用connectTo方法提高代码可续性详解

    这篇文章主要介绍了Java使用connectTo方法提高代码可续性,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • 启动Tomcat报错Unsupported major.minor version xxx的解决方法

    启动Tomcat报错Unsupported major.minor version xxx的解决方法

    这篇文章主要为大家详细介绍了启动Tomcat报错Unsupported major.minor version xxx的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • thymeleaf中前后端数据交互方法汇总

    thymeleaf中前后端数据交互方法汇总

    这篇文章主要介绍了thymeleaf中前后端数据交互小结,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2022-07-07
  • eclipse导入IntelliJ IDEA的maven项目的示例

    eclipse导入IntelliJ IDEA的maven项目的示例

    本篇文章主要介绍了eclipse导入IntelliJ IDEA的maven项目的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • java微信公众号支付示例详解

    java微信公众号支付示例详解

    这篇文章主要为大家详细介绍了java微信公众号支付示例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-12-12

最新评论