SpringBoot實現(xiàn)國際化i18n詳解
1.什么是國際化(i18n)
國際化(Internationalization,簡稱i18n)是指在軟件應(yīng)用中支持多種語言和文化的能力。通過國際化,應(yīng)用可以根據(jù)用戶的語言和地區(qū)設(shè)置,動態(tài)地顯示不同的文本內(nèi)容。本文將介紹如何在Spring Boot應(yīng)用中實現(xiàn)國際化,并提供完整的代碼示例。
2.代碼工程
在Spring Boot中實現(xiàn)國際化(i18n)可以通過以下步驟完成。我們將使用Spring的消息源(MessageSource)功能來支持多語言文本。
步驟 1: 創(chuàng)建項目
首先,創(chuàng)建一個新的Spring Boot項目??梢允褂肧pring 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: 創(chuàng)建國際化資源文件
在src/main/resources目錄下,創(chuàng)建一個名為messages的文件夾,并在其中創(chuàng)建不同語言的資源文件。例如:
messages.properties(默認語言,通常是英語)messages_zh.properties(中文)messages_fr.properties(法語)
每個文件的內(nèi)容如下:
messages.properties(默認語言)
greeting=Hello! farewell=Goodbye!
messages_zh.properties(中文)
greeting=你好! farewell=再見!
messages_fr.properties(法語)
greeting=Bonjour! farewell=Au revoir!
步驟 3: 配置MessageSource
在Spring Boot中,默認會自動配置MessageSource,但你可以自定義配置。創(chuàng)建一個配置類,例如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: 創(chuàng)建Controller
創(chuàng)建一個控制器來處理請求并返回國際化的消息:
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: 前端實現(xiàn)
如果你有前端頁面,可以通過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>
以上只是一些關(guān)鍵代碼,所有代碼請參見下面代碼倉庫
代碼倉庫
github.com/Harries/springboot-demo(i18n)
3.測試
啟動Spring Boot應(yīng)用,訪問http://127.0.0.1:8088/index.html。效果如下圖

4.總結(jié)
通過以上步驟,你可以在Spring Boot應(yīng)用中實現(xiàn)國際化。你可以根據(jù)用戶的語言偏好動態(tài)地返回不同的文本內(nèi)容。根據(jù)需要,你可以擴展更多語言和消息,并在前端實現(xiàn)語言切換功能。
到此這篇關(guān)于SpringBoot實現(xiàn)國際化i18n詳解的文章就介紹到這了,更多相關(guān)SpringBoot國際化i18n內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring中ApplicationContext的拓展功能詳解
這篇文章主要介紹了Spring中ApplicationContext的拓展功能詳解,相對于BeanFactory來說,ApplicationContext除了提供BeanFactory的所有功能外,還有一些其他的功能,主要包括國際化支持、資源訪問、事件傳遞,需要的朋友可以參考下2024-01-01
Java使用connectTo方法提高代碼可續(xù)性詳解
這篇文章主要介紹了Java使用connectTo方法提高代碼可續(xù)性,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08
啟動Tomcat報錯Unsupported major.minor version xxx的解決方法
這篇文章主要為大家詳細介紹了啟動Tomcat報錯Unsupported major.minor version xxx的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
thymeleaf中前后端數(shù)據(jù)交互方法匯總
這篇文章主要介紹了thymeleaf中前后端數(shù)據(jù)交互小結(jié),本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2022-07-07
eclipse導入IntelliJ IDEA的maven項目的示例
本篇文章主要介紹了eclipse導入IntelliJ IDEA的maven項目的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

