SpringBoot實現(xiàn)國際化i18n詳解
1.什么是國際化(i18n)
國際化(Internationalization,簡稱i18n)是指在軟件應用中支持多種語言和文化的能力。通過國際化,應用可以根據(jù)用戶的語言和地區(qū)設置,動態(tài)地顯示不同的文本內容。本文將介紹如何在Spring Boot應用中實現(xiàn)國際化,并提供完整的代碼示例。
2.代碼工程
在Spring Boot中實現(xiàn)國際化(i18n)可以通過以下步驟完成。我們將使用Spring的消息源(MessageSource)功能來支持多語言文本。
步驟 1: 創(chuàng)建項目
首先,創(chuàng)建一個新的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: 創(chuàng)建國際化資源文件
在src/main/resources
目錄下,創(chuàng)建一個名為messages
的文件夾,并在其中創(chuàng)建不同語言的資源文件。例如:
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
,但你可以自定義配置。創(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>
以上只是一些關鍵代碼,所有代碼請參見下面代碼倉庫
代碼倉庫
github.com/Harries/springboot-demo(i18n)
3.測試
啟動Spring Boot應用,訪問http://127.0.0.1:8088/index.html。效果如下圖
4.總結
通過以上步驟,你可以在Spring Boot應用中實現(xiàn)國際化。你可以根據(jù)用戶的語言偏好動態(tài)地返回不同的文本內容。根據(jù)需要,你可以擴展更多語言和消息,并在前端實現(xiàn)語言切換功能。
到此這篇關于SpringBoot實現(xiàn)國際化i18n詳解的文章就介紹到這了,更多相關SpringBoot國際化i18n內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java面試題沖刺第十九天--數(shù)據(jù)庫(4)
這篇文章主要為大家分享了最有價值的三道關于數(shù)據(jù)庫的面試題,涵蓋內容全面,包括數(shù)據(jù)結構和算法相關的題目、經(jīng)典面試編程題等,感興趣的小伙伴們可以參考一下2021-08-08淺談springboot項目中定時任務如何優(yōu)雅退出
這篇文章主要介紹了淺談springboot項目中定時任務如何優(yōu)雅退出?具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Springboot與Maven多環(huán)境配置的解決方案
多環(huán)境配置的解決方案有很多,我看到不少項目的多環(huán)境配置都是使用Maven來實現(xiàn)的,本文就實現(xiàn)Springboot與Maven多環(huán)境配置,感興趣的可以了解下2021-06-06spring boot整合spring-kafka實現(xiàn)發(fā)送接收消息實例代碼
這篇文章主要給大家介紹了關于spring-boot整合spring-kafka實現(xiàn)發(fā)送接收消息的相關資料,文中介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編一起來看看吧。2017-06-06