Springboot i18n 國際化

Springboot i18n 國際化

1.在資源目錄下新建文件夾i18n

2.以頁面開頭,創建一個properties,例如:hello.properties

3. 創建hello_zh_CN.properties

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-iPtxWuxG-1582526307300)(C:\Users\chang\AppData\Roaming\Typora\typora-user-images\image-20200224141828260.png)]

4.實現resolveLocale方法

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

5.將自己實現的地區解析器注入到spring容器

Spring 5.0後,WebMvcConfigurerAdapter被廢棄,取代的方法有兩種:

​ ①implements WebMvcConfigurer(官方推薦)

​ ②extends WebMvcConfigurationSupport

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

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

}

5.thymeleaf取值

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>國際化</title>
</head>
<body>

通過springMVC的LocaleResolver 地區解析器

<a th:href="@{/hello(l='zh_CN')}">中</a>
<a th:href="@{/hello(l='en_US')}">en</a>

<h1 th:text="#{hello.msg}"></h1>

</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章