1. 程式人生 > >一個簡單的示例在spring boot中實現國際化

一個簡單的示例在spring boot中實現國際化

最近在網上找了一個有關賬單管理的spring boot專案,其中有一部分是涉及顯示國際化資訊的,即將頁面上的中英文進行轉換。因為在這之前這部分內容沒有接觸過,所以在這記錄下過程。

中文效果圖如下所示:

英文效果圖如下所示:

 

從上面兩幅圖可以看出在切換中英文時有五個部分的內容傳送改變。分別是:使用者名稱(Username)、密碼(Password)、記住我(Remember Me)、登入(Sign)、重置(Rest)。

第一部分、先在resources目錄下新建一個i18n資料夾,並在該資料夾下新建一個Resource Bundle.如下圖所示:

 

並在跳出的彈框內寫入以下資訊:

 

點選“OK”後就會在i18n目錄下生成3個字尾名為“.properties”的檔案。如下所示:

第二部分、分別在這三個檔案中填入相應資訊。

login.properties表示預設顯示的資訊。login.password、login.remember、login.reset、login.submit、login.username是自己設定的key值,用於在HTML中顯示。後面的是將要顯示的內容。

1 login.password=密碼
2 login.remember=記住我
3 login.reset=重置
4 login.submit=登入
5 login.username=使用者名稱

 login_en_US.properties

1 login.password=Password
2 login.remember=Remember Me
3 login.reset=Rest
4 login.submit=Sign
5 login.username=Username

login_zh_CN.properties

1 login.password=密碼
2 login.remember=記住我
3 login.reset=重置
4 login.submit=登入
5 login.username=使用者名稱

第三部分、在HTML相應位置填入key值,並在點選“中文”或“English”發出不同請求資訊。

注意:在這個專案中使用的模板是thymeleaf,因此需要現在開始的html標籤內引入該模板的標籤。

根據thymeleaf的文件

顯示國際化資訊時用到的“#{}”而不是"${}"。

由於這個“記住我”是<input>單標籤的沒有標籤體,根據thymeleaf文件發現需要使用"[[#{}]]"或“[(#{})]”行內表示式。

當點選“中文”時附帶請求資訊“zh_CN”,點選英文時附帶請求資訊“en_US”.

login.html程式碼如下所示:

 1 <!DOCTYPE html>
 2 <html xmlns:th="http://www.thymeleaf.org">
 3 <head lang="en" th:replace="main/public :: #public_head">
 4 
 5 </head>
 6 <body class="login_bg">
 7     <section class="loginBox">
 8         <header class="loginHeader">
 9             <h1>輕舟萬里賬單管理系統</h1>
10         </header>
11         <section class="loginCont">
12             <!--<div style="color:red; margin-left: 130px">使用者名稱錯誤!</div>-->
13             <form class="loginForm" action="../main/index.html">
14                 
15                 <div class="inputbox">
16                     <label for="user" th:text="#{login.username}">Username</label>
17                     <input id="user" type="text" name="username"  required/>
18                 </div>
19                 <div class="inputbox">
20                     <label for="mima" th:text="#{login.password}">Password</label>
21                     <input id="mima" type="password" name="password"  required/>
22                 </div>
23                 <div class="subBtn">
24                         <input type="checkbox"> [[#{login.remember}]]
25                 </div>
26                 <br/>
27                 <div class="subBtn">
28                     <input type="submit" th:value="#{login.submit}" value="Sign" />
29                     <input type="reset" th:value="#{login.reset}" value="Reset"/>
30                 </div>
31                 <br/>
32                 <div style="margin-left: 100px;">
33                     <a href="#" th:href="@{/index.html(l='zh_CN')}">中文</a>
34                     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
35                     <a href="" th:href="@{/index.html(l='en_US')}">English</a>
36                 </div>
37             </form>
38         </section>
39     </section>
40 </body>
41 </html>
login.html

 

第四部分、設定區域解析器

在頁面上顯示中文還是英文是由請求資訊頭中“accept-language”的決定的,預設是中文。我們只要將點選所附帶的請求資訊傳遞給“accept-language”就會使頁面的中英文改變。

spring boot中有一個WebMvcAutoConfiguration類,提供了本地區域解析器。如下圖所示:

該本地區域解析器上有個註解@ConditionalOnMissingBean表示如果容器中沒有這個bean,就將這個bean放到容器中,如果有就使用已經存在的。

從下面的程式碼片段中可以看到有一個請求頭本地區域解析器AcceptHeaderLocaleResolver實現了LocaleResolver介面。

因此我們可以在component包下新建一個自定義區域解析器MyLocaleResolver,該類需要實現介面LocaleResolver,重寫方法,根據請求的引數構造一個Local返回。

 1 package club.nipengfei.springboot.component;
 2 
 3 import org.springframework.web.servlet.LocaleResolver;
 4 import org.thymeleaf.util.StringUtils;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.util.Locale;
 9 
10 /**
11  * 自定義區域解析器
12  */
13 public class MyLocaleResolver implements LocaleResolver {
14     @Override
15     public Locale resolveLocale(HttpServletRequest httpServletRequest) {
16         // 獲取自定義請求頭資訊
17         String l = httpServletRequest.getParameter("l");
18         // 獲取系統預設的區域資訊
19         Locale locale = Locale.getDefault();
20         if (!StringUtils.isEmpty(l)){
21             String[] split = l.split("_");
22             // 接收第一個引數為語言程式碼,第二個引數為國家程式碼
23             locale = new Locale(split[0],split[1]);
24         }
25         return locale;
26     }
27 
28     @Override
29     public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
30 
31     }
32 }

 

將其新增到容器中,在config包下新建一個MySpringMvcConfigure,在該類的localeResolver方法中返回LocaleResolver,注意使用註解@Bean。程式碼如下所示:

 1 package club.nipengfei.springboot.config;
 2 
 3 import club.nipengfei.springboot.component.MyLocaleResolver;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.servlet.LocaleResolver;
 7 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 8 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 9 
10 @Configuration
11 public class MySpringMvcConfigure {
12 
13     @Bean
14     public WebMvcConfigurer webMvcConfigurer(){
15         return new WebMvcConfigurer() {
16 
17             // 新增檢視控制器
18             @Override
19             public void addViewControllers(ViewControllerRegistry registry) {
20 
21                 registry.addViewController("/").setViewName("/main/login");
22                 registry.addViewController("/index.html").setViewName("/main/login");
23             }
24         };
25     }
26 
27     // 區域解析器
28     @Bean
29     public LocaleResolver localeResolver(){
30         return new MyLocaleResolver();
31     }
32 }

 

第五部分、在這過程中遇到的問題。

  1. 中英文顯示亂碼,解決方法是修改properties檔案編碼,改為UTF-8。參考:解決 IntelliJ IDEA 中 i18n國際化 中文亂碼問題。
  2. 無法訪問到login頁面,因為login.html頁面在template/main目錄下。解決方法是新增檢視控制器。