首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

在Spring Boot中的实现国际化(i18n)

  • 24-12-14 16:03
  • 4045
  • 9491
juejin.cn

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

    xml
    代码解读
    复制代码
    <artifactId>i18nartifactId> <properties> <maven.compiler.source>8maven.compiler.source> <maven.compiler.target>8maven.compiler.target> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-autoconfigureartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> dependencies>

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

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

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

每个文件的内容如下:

messages.properties(默认语言)

ini
代码解读
复制代码
greeting=Hello! farewell=Goodbye!

messages_zh.properties(中文)

ini
代码解读
复制代码
greeting=你好! farewell=再见!

messages_fr.properties(法语)

ini
代码解读
复制代码
greeting=Bonjour! farewell=Au revoir!

步骤 3: 配置MessageSource

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

kotlin
代码解读
复制代码
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

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

kotlin
代码解读
复制代码
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:

xml
代码解读
复制代码
html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Internationalization Exampletitle> <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">Englishoption> <option value="zh">中文option> <option value="fr">Françaisoption> 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/spr…(i18n)

3.测试

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

il8n

4.总结

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

注:本文转载自juejin.cn的HBLOG的文章"https://juejin.cn/post/7447787291765702683"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

142
代码人生
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top