欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot實(shí)現(xiàn)國(guó)際化i18n詳解

 更新時(shí)間:2024年12月15日 08:14:04   作者:HBLOG  
國(guó)際化(Internationalization,簡(jiǎn)稱i18n)是指在軟件應(yīng)用中支持多種語(yǔ)言和文化的能力,本文將介紹如何在Spring?Boot應(yīng)用中實(shí)現(xiàn)國(guó)際化,需要的可以參考下

1.什么是國(guó)際化(i18n)

國(guó)際化(Internationalization,簡(jiǎn)稱i18n)是指在軟件應(yīng)用中支持多種語(yǔ)言和文化的能力。通過(guò)國(guó)際化,應(yīng)用可以根據(jù)用戶的語(yǔ)言和地區(qū)設(shè)置,動(dòng)態(tài)地顯示不同的文本內(nèi)容。本文將介紹如何在Spring Boot應(yīng)用中實(shí)現(xiàn)國(guó)際化,并提供完整的代碼示例。

2.代碼工程

在Spring Boot中實(shí)現(xiàn)國(guó)際化(i18n)可以通過(guò)以下步驟完成。我們將使用Spring的消息源(MessageSource)功能來(lái)支持多語(yǔ)言文本。

步驟 1: 創(chuàng)建項(xiàng)目

首先,創(chuàng)建一個(gè)新的Spring Boot項(xiàng)目??梢允褂肧pring Initializr(start.spring.io/)來(lái)生成項(xiàng)目,選擇以下…

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)建國(guó)際化資源文件

src/main/resources目錄下,創(chuàng)建一個(gè)名為messages的文件夾,并在其中創(chuàng)建不同語(yǔ)言的資源文件。例如:

  • messages.properties(默認(rèn)語(yǔ)言,通常是英語(yǔ))
  • messages_zh.properties(中文)
  • messages_fr.properties(法語(yǔ))

每個(gè)文件的內(nèi)容如下:

messages.properties(默認(rèn)語(yǔ)言)

greeting=Hello!
farewell=Goodbye!

messages_zh.properties(中文)

greeting=你好!
farewell=再見!

messages_fr.properties(法語(yǔ))

greeting=Bonjour!
farewell=Au revoir!

步驟 3: 配置MessageSource

在Spring Boot中,默認(rèn)會(huì)自動(dòng)配置MessageSource,但你可以自定義配置。創(chuàng)建一個(gè)配置類,例如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)建一個(gè)控制器來(lái)處理請(qǐng)求并返回國(guó)際化的消息:

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: 前端實(shí)現(xiàn)

如果你有前端頁(yè)面,可以通過(guò)AJAX請(qǐng)求獲取國(guó)際化文本。例如,使用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)鍵代碼,所有代碼請(qǐng)參見下面代碼倉(cāng)庫(kù)

代碼倉(cāng)庫(kù)

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

3.測(cè)試

啟動(dòng)Spring Boot應(yīng)用,訪問(wèn)http://127.0.0.1:8088/index.html。效果如下圖

4.總結(jié)

通過(guò)以上步驟,你可以在Spring Boot應(yīng)用中實(shí)現(xiàn)國(guó)際化。你可以根據(jù)用戶的語(yǔ)言偏好動(dòng)態(tài)地返回不同的文本內(nèi)容。根據(jù)需要,你可以擴(kuò)展更多語(yǔ)言和消息,并在前端實(shí)現(xiàn)語(yǔ)言切換功能。

到此這篇關(guān)于SpringBoot實(shí)現(xiàn)國(guó)際化i18n詳解的文章就介紹到這了,更多相關(guān)SpringBoot國(guó)際化i18n內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • spring boot整合spring-kafka實(shí)現(xiàn)發(fā)送接收消息實(shí)例代碼

    spring boot整合spring-kafka實(shí)現(xiàn)發(fā)送接收消息實(shí)例代碼

    這篇文章主要給大家介紹了關(guān)于spring-boot整合spring-kafka實(shí)現(xiàn)發(fā)送接收消息的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)看看吧。
    2017-06-06
  • java設(shè)計(jì)模式之委派模式原理分析

    java設(shè)計(jì)模式之委派模式原理分析

    這篇文章主要介紹了java設(shè)計(jì)模式之委派模式原理分析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • springboot如何配置Filter過(guò)濾器

    springboot如何配置Filter過(guò)濾器

    這篇文章主要介紹了springboot如何配置Filter過(guò)濾器問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java png圖片修改像素rgba值的操作

    Java png圖片修改像素rgba值的操作

    這篇文章主要介紹了Java png圖片修改像素rgba值的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 最新評(píng)論