1. 程式人生 > 其它 >【狂神springboot筆記】SpringBoot實現國際化

【狂神springboot筆記】SpringBoot實現國際化

1、IDEA新增語言配置檔案

在resources下建立i18n(國際化的縮寫,一般建立這個)資料夾,然後建立對應的配置檔案,這裡比較巧妙的是建立多個檔案他會自動幫你生產Resource Bundle '檔名'

點選下面這個按鈕,就可以快捷新增其他語言配置檔案,例如新增en_US就會自動生成美國的語言配置檔案:

2、配置檔案視覺化插入內容

點選左下角這個按鈕,就如視覺化插入內容的視窗

下面是寫入內容的截圖

3、程式碼中呼叫

3.1 這裡對應的AutoConfiguration是 MessageSourceAutoConfiguration

public class MessageSourceAutoConfiguration {
    private static final Resource[] NO_RESOURCES = new Resource[0];

    public MessageSourceAutoConfiguration() {
    }

    @Bean
    @ConfigurationProperties(
        prefix = "**spring.messages**"
    )

可以看到這裡的字首是spring.messages

新增對應的引數在application.properties裡面

//配置檔案的真實位置
spring.messages.basename=i18n.login

3.2 頁面獲取國際化的值

Thymeleaf文件中message的取值操作是#{}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="#{login.tip}">"please login in"</h1>
<div th:text="${msg}"></div>
<div th:each="book : ${books}" th:text="${book}">books</div>
</body>
</html>

結果:

顯示成功!

3.3 配置國際化解析

在Spring中有一個國際化的Locale (區域資訊物件);裡面有一個叫做LocaleResolver (獲取區域資訊物件)的解析器!

我們去我們webmvc自動配置檔案,尋找一下!看到SpringBoot預設配置:

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
    // 容器中沒有就自己配,有的話就用使用者配置的
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    // 接收頭國際化分解
    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    return localeResolver;
}

AcceptHeaderLocaleResolver 這個類中有一個方法


public Locale resolveLocale(HttpServletRequest request) {
    Locale defaultLocale = this.getDefaultLocale();
    // 預設的就是根據請求頭帶來的區域資訊獲取Locale進行國際化
    if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
        return defaultLocale;
    } else {
        Locale requestLocale = request.getLocale();
        List<Locale> supportedLocales = this.getSupportedLocales();
        if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
            Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
            if (supportedLocale != null) {
                return supportedLocale;
            } else {
                return defaultLocale != null ? defaultLocale : requestLocale;
            }
        } else {
            return requestLocale;
        }
    }
}

那假如我們現在想點選連結讓我們的國際化資源生效,就需要讓我們自己的Locale生效!

我們去自己寫一個自己的LocaleResolver,可以在連結上攜帶區域資訊!

修改一下前端頁面的跳轉連線:

<!-- 這裡傳入引數不需要使用 ?使用 (key=value)-->
<a class="btn btn-sm" th:href="@{/test.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/test.html(l='en_US')}">English</a>

為了讓我們的區域化資訊能夠生效,我們需要再配置一下這個元件!在我們自己的MvcConofig下新增bean;

//自己的檢視解析器
@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("test");
        registry.addViewController("/test.html").setViewName("test");
    }

@Bean
    public LocaleResolver localeResolver() {
      return new MyLocalResolver();
    }

結果圖: