1. 程式人生 > >【spring 國際化】springMVC、springboot國際化處理詳解

【spring 國際化】springMVC、springboot國際化處理詳解

在web開發中我們常常會遇到國際化語言處理問題,那麼如何來做到國際化呢?

你能get的知識點?

  1. 使用springgmvc與thymeleaf進行國際化處理。
  2. 使用springgmvc與jsp進行國際化處理。
  3. 使用springboot與thymeleaf進行國際化處理。

目錄

  • 你能get的知識點?
  • 你必須要知道的概念
  • 一:使用springgmvc與thymeleaf進行國際化處理。
  • 二: 使用springgmvc與jsp進行國際化處理。
  • 三:使用springboot與thymeleaf進行國際化處理。
  • 問題

你必須要知道的概念

關於i18n:

i18n(其來源是英文單詞
internationalization的首末字元i和n,18為中間的字元數)是“國際化”的簡稱。在資訊領域,國際化(i18n)指讓產品(出版物,軟體,硬體等)無需做大的改變就能夠適應不同的語言和地區的需要。對程式來說,在不修改內部程式碼的情況下,能根據不同語言及地區顯示相應的介面。
在全球化的時代,國際化尤為重要,因為產品的潛在使用者可能來自世界的各個角落。通常與i18n相關的還有L10n(“本地化”的簡稱)。

一:使用springgmvc與thymeleaf進行國際化處理。


1、在專案spring的Spring MVC配置檔案springmvc.xml中,你需要配置

  • 資原始檔繫結器ResourceBundleMessageSource
  • SessionLocaleResolver(用於將Locale物件儲存於Session中供後續使用)
  • LocaleChangeInterceptor(用於獲取請求中的locale資訊,將其轉為Locale物件,獲取LocaleResolver物件)。
    <!--   使用ResourceBundleMessageSource實現國際化資源-->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" value="messages"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en_US"/>
    </bean>
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="lang"/>
        </bean>
    </mvc:interceptors>

2、在控制器中新增方法localeChange處理國際化,並注入ResourceBundleMessageSource的Bean例項

    @Autowired
    private ResourceBundleMessageSource messageSource;

    @GetMapping("/localeChange")
    public String localeChange(Locale locale){
        String userName = messageSource.getMessage("userName",null,locale);
        String passWord = messageSource.getMessage("passWord",null,locale);
        System.out.println(userName+passWord);
        return "login";
    }

3、建立國際化資源屬性檔案messages_en_US.propertiesmessages_zh_CN.properties
注意這兩個檔案的命名格式,否則解析會出錯,
並且我這裡的兩個檔案就是位於我的resources目錄下,當你新建這兩個檔案後,他會自動給你歸檔,不要以為我的這兩個上面還有一層,你也跟著建一個資料夾。

1、messages_en_US.properties
userName=userName
passWord=password

2、messages_zh_CN.properties
userName=使用者名稱
passWord=密碼

4、新建html,用於最終的顯示,這裡使用的是thymeleaf模板引擎,沒有做springmvc與thymeleaf的整合可以看我的另一篇文章 springmvc與thymeleaf的整合

<!--
  @Author: lomtom
  @Date: 2020/4/19
  @Time: 16:51
  @Email: [email protected]
  -->

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<h2 th:text="#{userName}+' '+#{passWord}"></h2>
<a href="localeChange?lang=en_US">英文</a>
<a href="localeChange?lang=zh_CN">中文</a>
</body>
</html>

最終的效果:

二: 使用springgmvc與jsp進行國際化處理。

這裡的前三部與上面相同,唯一有區別的就是最終檢視的顯示,使用jsp,就要用到JSTL標籤,這裡需要引入JSTL的message標籤。

即在頭部加入<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

然後通過<spring:message>元素的key屬性輸出資源屬性檔案中的key所對應的值,最終的jsp是這樣的。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
    <title>login</title>
</head>
<body>
    <p><spring:message code="userName"/></p>
    <p><spring:message code="password"/></p>
    <a href="localeChange?lang=en_US">英文</a>
    <a href="localeChange?lang=zh_US">中文</a>
</body>
</html>

依次點選“中文”和“英文”連結,可以看到<spring:message>元素顯示的文字能夠根據所傳遞的語言來動態展現。

三:使用springboot與thymeleaf進行國際化處理。

沒有做springmvc與thymeleaf的整合可以看我的另一篇文章 springmvc與thymeleaf的整合

1、建立配置檔案,抽取頁面要顯示的訊息

2、springboot已經配置好了元件,加入即可

spring:
#    讓springboot來管理配置檔案
  messages:
    basename: i18n.login

3、讓頁面獲取即可(預設根據瀏覽器語言來切換),利用thymeleaf

<button type="submit" class="btn btn-default" th:text="#{login.btn}">Sign in</button>

4、根據連結來進行語言的切換
原理:國際化locale(區域資訊物件),如果自定義了,就是用自己的,而不是系統的

<a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">[[#{login.zh}]]</a>
<a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">[[#{login.en}]]</a>
<a class="btn btn-sm" th:href="@{/index.html(l=kor_KR)}">[[#{login.kor}]]</a>

5、解析器,因為我們設定了自己的區域資訊物件,所以我們需要書寫自己的解析器。並且注入到容器中。

1、新建一個LocaleResolver 
public class MyLocaleResolver implements LocaleResolver {
    @Override
    //解析區域資訊
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.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) {

    }
}


2、在config檔案中加入到容器中
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
	@Bean
	public LocaleResolver localeResolver(){
	    return new MyLocaleResolver();
	}
}

這個寫的時間過於久遠,所以貼出程式碼,感興趣的,可以自己研究研究:

1、html

<!--
  User: 歐陽隆桐
  Date: 2019/12/22
  Time: 16:42
  -->
<!DOCTYPE html>
<html lang="ch"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>[[#{login.title}]]</title>
    <link rel="stylesheet" href="/webjars/bootstrap/4.4.1/css/bootstrap.css" th:href="@{/webjars/bootstrap/4.4.1/css/bootstrap.css}">
    <script src="/webjars/jquery/3.3.1/jquery.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
    <script src="/webjars/bootstrap/4.4.1/js/bootstrap.js" th:src="@{/webjars/bootstrap/4.4.1/js/bootstrap.js}"></script>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <form class="form-horizontal" role="form" th:action="@{/user/login}" method="post">
                <div class="form-group  text-center">
                    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
                    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
                </div>
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label" th:text="#{login.username}">Username</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control"  name="username" id="username" />
                    </div>
                </div>
                <div class="form-group">
                    <label for="password" class="col-sm-2 control-label" th:text="#{login.password}">Password</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" name="password" id="password" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <div class="checkbox">
                            <label><input type="checkbox" />[[#{login.remember}]]</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default" th:text="#{login.btn}">Sign in</button>
                    </div>
                </div>
                <div class="form-group  text-center">
                    <p class="mt-5 mb-3 text-muted">@ 2019</p>
                    <a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">[[#{login.zh}]]</a>
                    <a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">[[#{login.en}]]</a>
                    <a class="btn btn-sm" th:href="@{/index.html(l=kor_KR)}">[[#{login.kor}]]</a>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

2、properties

1、預設
login.btn=登入
login.en=英文
login.kor=韓文
login.password=密碼
login.remember=記住我
login.tip=請登入
login.title=登入
login.username=使用者名稱
login.zh=中文

2、英文
login.btn=Sign in
login.en=English
login.kor=Korean
login.password=Password
login.remember=Remember me
login.tip=Please sign in
login.title=Login
login.username=Username
login.zh=Chinese

3、韓文
login.btn=로그인
login.en=영어
login.kor=한글
login.password=암호
login.remember=저를 기억하세요
login.tip=로그인하십시오.
login.title=로그인
login.username=사용자 이름
login.zh=중국어

4、中文
login.btn=登入
login.en=英文
login.kor=韓文
login.password=密碼
login.remember=記住我
login.tip=請登入
login.title=登入
login.username=使用者名稱
login.zh=中文

3、java

1、LocaleResolver
/**
 * 可以在連線上攜帶區域資訊
 */

public class MyLocaleResolver implements LocaleResolver {
    @Override
    //解析區域資訊
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.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) {

    }
}

2、config
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
	@Bean
	public LocaleResolver localeResolver(){
	    return new MyLocaleResolver();
	}
}

4、yml

spring:
#    讓springboot來管理配置檔案
  messages:
    basename: i18n.login

問題

描述:顯示中文時亂碼
解決:將國際化資源屬性檔案的編碼格式設定為UTF-8即可,當然也可以把整個專案編碼格式都設為UTF-8

相關推薦

no