springboot 使用i18n進行國際化

一、i18n介紹html

  i18n(其來源是英文單詞 internationalization的首末字符i和n,18爲中間的字符數)是「國際化」的簡稱。在資訊領域,國際化(i18n)指讓產品(出版物,軟件,硬件等)無需作大的改變就可以適應不一樣的語言和地區的須要。對程序來講,在不修改內部代碼的狀況下,能根據不一樣語言及地區顯示相應的界面。前端

二、頁面元素國際化:jquery

  pom文件引入thymeleaf依賴:git

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

  新增一個html文件hello.html:github

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
<head>
    <title>hello</title>
</head>
<body>
    <span>
        <label th:text="#{welcome}"></label>
    </span>
</body>
</html>    

  SpringBoot 默認支持國際化的,在resources/下定義國際化文件,名稱必須以messages開頭,由於 MessageSourceAutoConfiguration 類中指定了前綴。spring

messages.properties
welcome = 歡迎使用i18n(默認)
messages_zh_CN.properties
welcome = 歡迎使用i18n(中文)
messages_en_US.properties
welcome = welcome to use i18n(english)

  訪問接口springboot

@Controller
public class HelloController {

    @RequestMapping(value = "hello")
    public String hello() {
        return "hello";
    }
}

  啓動項目訪問http://localhost:8080/hello就能夠看到效果app

三、修改默認messages配置前綴ide

  上面使用的是messages默認的配置,即直接放在resources/目錄下,通常項目中會使用本身的目錄存放,如放在resources/i18n/目錄下spring-boot

  在application配置中添加

#i18n
spring:
  messages:
    encoding: UTF-8
    basename: i18n/messages

  加好以後從新訪問便可

四、代碼中使用國際化

   //注入 MessageSource 對象,經過 getMessage 方法獲取信息
    @Autowired
    private MessageSource messageSource;
    
    //使用
    messageSource.getMessage("welcome", null, locale);

說明:第一個參數是國際化文件的key,第二個參數是key對應value中的佔位符數據(如welcome=歡迎使用{0}中的{0}就是佔位符,0表示是第一個,對應數據中的第一個值),第三個是當前區域

五、會話區域解析器SessionLocaleResolver

   注入 Bean

//注入 Bean,會話區域解析器只針對當前會話有效
@Bean
public LocaleResolver localeResolver() {
      SessionLocaleResolver slr = new SessionLocaleResolver();
      //設置默認區域,
      slr.setDefaultLocale(Locale.ENGLISH);
      return slr;
}

  接口控制器:

   @RequestMapping("/i18n")
    public String changeSessionLanauage(HttpServletRequest request, String lang){
        System.out.println(lang);
        if(CommonConsts.LANG_ZH.equals(lang)){
            //代碼中便可經過如下方法進行語言設置
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("zh","CN"));
        }else if(CommonConsts.LANG_EN.equals(lang)){
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("en","US"));
        }
        return "redirect:/hello";
    }

其中request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("zh","CN"));用於切換當前會話區域

  前端頁面hello.html修改:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <script th:src="@{js/jquery.min.js}"></script>
    <script th:src="@{js/hello.js}"></script>
</head>
<body>
<p><label th:text="#{welcome}"></label></p><br/>
<span th:text="#{lang}"></span>
<select id="locales">
    <option value=""></option>
    <option value="zh" th:text="zh"></option>
    <option value="en" th:text="en"></option>
</select>
</body>
</html>

  hello.js文件

$(function () {
    $("#locales").change(function() {
        var lang = $("#locales").val();
        if (lang != "") {
            window.location.replace("/i18n?lang=" + lang);
        }
    });
});

  須要同時做用於Cookie時,修改接口控制器:

    @RequestMapping("/i18n2")
    public String changeSessionLanauage2(HttpServletRequest request, HttpServletResponse response, String lang){
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if(CommonConsts.LANG_ZH.equals(lang)){
            localeResolver.setLocale(request, response, new Locale("zh","CN"));
        }else if(CommonConsts.LANG_EN.equals(lang)){
            localeResolver.setLocale(request, response, new Locale("en","US"));
        }
        return"redirect:/hello";
    }

六、使用參數進行語言切換

使用攔截器來攔截請求接口中的參數來實現語言切換

  注入區域切換攔截bean

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
     //對請求路徑中的參數lang進行攔截
        lci.setParamName("lang");

        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

  hello.html添加修改:

點擊切換語言:
<a href="/hello?lang=zh_CN">簡體中文</a> &nbsp;&nbsp;
<a href="/hello?lang=en_US">English(US)</a><br>

項目啓動後點擊連接測試效果便可

七、訪問亂碼問題解決

 見springboot使用i18n亂碼

項目源碼:github

相關文章
相關標籤/搜索