前言
在很多網站我們可以看到可以切換語言的按鈕,如果網站需要面向海外用戶,那么實現網站語言國際化就顯得非常必要。在 Spring Boot 中,我們可以非常方便地實現這個語言國際化的功能,下面就開始動手來實踐一個可以中英切換的登錄頁面吧。
創建項目
項目結構圖如下:
1.png
這里的登錄頁面使用的是 Bootstrap 官方的一個實例,下載下來,把相關靜態資源文件導入到 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, 登錄頁面,把需要進行語言替換的地方換成 thymeleaf 標簽
<!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 目錄,創建 login.properties, login_en_US.properties, login_zh_CN.properties, 注意這里名字不要寫錯, 語言資源文件格式: 自定義標識語言代碼國家地區.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配置
# (包名.基礎名)
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, 根據請求切換語言資源
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: 區域解析器, 根據請求的值來返回對應的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) {
//設置對"/"的請求映射到login
//如果沒有邏輯業務,沒有必要用控制器方法對請求進行映射
registry.addViewController("/").setViewName("login");
}
/**
* 注冊我們自定義的區域解析器,
* 一旦將區域解析器注冊到Spring容器中
* 則SpingBoot默認提供的區域解析器將不會自動注冊
*/
@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";
}
}
運行演示
項目啟動后,訪問 8080 端口,默認顯示是中文
4.png
點擊 English 可以切換到英文
3.png
項目已上傳至 Github: https://github.com/yekongle/springboot-code-samples/tree/master/springboot-i18n-sample , 希望對小伙伴們有幫助哦。