在一些有些的网站,尤其是一些文档网站,我们都能看到国际化的身影,比如:vue官网
在springboot中,我们应该怎么实现国际化呢?下面,我们对这个问题进行讨论和解决。
第一步
我们要借助properties文件
实现国际化,我们需要创建如下目录及文件( i18n:internationalization中i和n之间有18的英文单词
)
resources
-- i18n(文件夹)
-- xxx.properties
-- xxx_en_US.properties
-- xxx_zh_CN.properties
当我们手动创建完demo.properties
和demo_en_US.properties
文件后,IEDA会自动它们进行合并到虚拟的Resource Bundle 'xxx'目录
如下:
我们可以通过下面的方式创建第三个properties文件,如下:
①:Resource Bundle ‘xxx’ ——> New ——> Add Pro…
②:+ ——> 编辑’zh_CN’
③:完成
第二步
我们要实现国际化,在demo_en_US.properties
和demo_zh_CN.properties
中编写相同格式但是不同语言的内容。借助IDEA,我们可以很方便的完成格式但是不同语言的编写。
① 打开3个文件中的任意一个,点击Resource Bundle
② 添加key名
③ 编写value值
第三步
① 编写MyLocaleResolver组件
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取client端传递的"language"参数
String language = httpServletRequest.getParameter("language");
//获取默认的设置的"地区"和"语言"
Locale locale = Locale.getDefault();
//判断接收到client端传递的"language"是否为空
if (!StringUtils.isEmpty(language)) {
String[] split = language.split("_"); //通过"_"进行分解language(格式如:zh_CN)
locale = new Locale(split[0], split[1]); //手动创建前端的地区和语言
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
② 将该组件添加到Bean中
package com.example.demo.config;
import com.example.demo.component.MyLocaleResolver;
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.WebMvcConfigurer;
/**
* @author huxuehao
* @create 2021-08-11-18:32
*/
@Configuration
public class MyConfig implements WebMvcConfigurer {
// 自定义的国际化组件添加到Bean(容器)中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
③ 在application.properties
中添加配置参数,生效配置
spring.messages.basename=i18n.login
第四步
编写测试的html(demo_i18n.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="box">
<div>
<strong th:text="#{demo.usernameTip}"></strong>:
<strong th:text="#{demo.username}"></strong>
</div>
<div>
<strong th:text="#{demo.ageTip}"></strong>:
<strong th:text="#{demo.age}"></strong>
</div>
<div>
<strong th:text="#{demo.describeTip}"></strong>:
<strong th:text="#{demo.describe}"></strong>
</div>
<div>
<a th:href="@{/demo_i18n(language='zh_CN')}" th:text="#{demo.language.zh}"></a><br>
<a th:href="@{/demo_i18n(language='en_US')}" th:text="#{demo.language.en}"></a>
</div>
</div>
</body>
</html>
测试
卓越不是单一的举动,而是习惯…