Spring Boot2 實(shí)戰(zhàn)系列之語言國際化

前言

在很多網(wǎng)站我們可以看到可以切換語言的按鈕,如果網(wǎng)站需要面向海外用戶,那么實(shí)現(xiàn)網(wǎng)站語言國際化就顯得非常必要。在 Spring Boot 中,我們可以非常方便地實(shí)現(xiàn)這個語言國際化的功能,下面就開始動手來實(shí)踐一個可以中英切換的登錄頁面吧。

創(chuàng)建項(xiàng)目

項(xiàng)目結(jié)構(gòu)圖如下:


1.png

這里的登錄頁面使用的是 Bootstrap 官方的一個實(shí)例,下載下來,把相關(guān)靜態(tài)資源文件導(dǎo)入到 resources 目錄就好。


2.png

pom 依賴如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>top.yekongle</groupId>
    <artifactId>springboot-i18n-sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-i18n-sample</name>
    <description>i18n sample for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

代碼編寫

login.html, 登錄頁面,把需要進(jìn)行語言替換的地方換成 thymeleaf 標(biāo)簽

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!-- Bootstrap core CSS -->
        <link href="asserts/css/bootstrap.min.css" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" rel="stylesheet">
    </head>
 
    <body class="text-center">
        <form class="form-signin" action="dashboard.html">
            <img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
            <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
            <label class="sr-only">Username</label>
            <input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
            <label class="sr-only">Password</label>
            <input type="password" class="form-control" th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
          <input type="checkbox" value="remember">  [[#{login.remember}]]
        </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" th:text="#{login.btn}" type="submit">Sign in</button>
            <p class="mt-5 mb-3 text-muted">? 2017-2020</p>
            <a class="btn btn-sm" th:href="@{/login(l='zh_CN')}">中文</a>
            <a class="btn btn-sm" th:href="@{/login(l='en_US')}">English</a>
        </form>
    </body>
</html>

在 resources 下新建一個 i18n 目錄,創(chuàng)建 login.properties, login_en_US.properties, login_zh_CN.properties, 注意這里名字不要寫錯, 語言資源文件格式: 自定義標(biāo)識語言代碼國家地區(qū).properties

login.properties

login.btn=登陸
login.password=密碼
login.remember=記住我
login.tip=請登錄
login.username=用戶名

login_en_US.properties

login.btn=Sign in
login.password=Password
login.remember=remember-me
login.tip=Please sign in
login.username=UserName

login_zh_CN.properties

login.btn=登錄
login.password=密碼
login.remember=記住我
login.tip=請登錄
login.username=用戶名

編輯全局配置文件 application.properties

# 國際化i18n配置
# (包名.基礎(chǔ)名)
spring.messages.basename=i18n.login
spring.messages.encoding=UTF-8

# Thymeleaf 配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 禁止緩存
spring.thymeleaf.cache=false

I18nLocaleResolver.java, 根據(jù)請求切換語言資源

package top.yekongle.i18n.config;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import lombok.extern.slf4j.Slf4j;

/** 
* Description: 區(qū)域解析器, 根據(jù)請求的值來返回對應(yīng)的Locale
* Author: Yekongle  
*/
@Slf4j
public class I18nLocaleResolver 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]);
        }
        log.info("Local Country: {}, language: {}", locale.getCountry(), locale.getLanguage());
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }    

}

WebMvcConfig.java, 請求配置

package top.yekongle.i18n.config;

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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/** 
* @Description: I18n config
* @Author: Yekongle 
* @Date: Mar 22, 2020
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //設(shè)置對"/"的請求映射到login
        //如果沒有邏輯業(yè)務(wù),沒有必要用控制器方法對請求進(jìn)行映射  
        registry.addViewController("/").setViewName("login");
    }
 
 
    /**
     * 注冊我們自定義的區(qū)域解析器,
     * 一旦將區(qū)域解析器注冊到Spring容器中
     * 則SpingBoot默認(rèn)提供的區(qū)域解析器將不會自動注冊
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new I18nLocaleResolver();
    }
 
}

LoginController.java

package top.yekongle.i18n.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* @Author: Yekongle 
* @Date: Mar 22, 2020
*/
@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

運(yùn)行演示

項(xiàng)目啟動后,訪問 8080 端口,默認(rèn)顯示是中文


4.png

點(diǎn)擊 English 可以切換到英文


3.png

項(xiàng)目已上傳至 Github: https://github.com/yekongle/springboot-code-samples/tree/master/springboot-i18n-sample , 希望對小伙伴們有幫助哦。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容