SpringBoot 快速支持国际化i18n
学习目标
- 快速学会如何在工程中支持国际化语言。
快速查阅
专题阅读:《SpringBoot 布道系列》
— Hey Man,Don't forget to Star or Fork . —
项目结构:

使用教程
一、后台国际化
1、配置国际化参数
默认解析器:LocaleResolver 用于设置当前会话的默认的国际化语言。
默认拦截器:LocaleChangeInterceptor 指定切换国际化语言的参数名。例如?lang=zh_CN 表示读取国际化文件messages_zh_CN.properties。
/**
* 配置国际化语言
*/
@Configuration
public class LocaleConfig {
/**
* 默认解析器 其中locale表示默认语言
*/
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
/**
* 默认拦截器 其中lang表示切换语言的参数名
*/
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
}
2、添加国际化文件
首先在配置文件 application.yml 填写国际化文件的相对路径,表示读取classpath:/static/i18n/messages_language_country.properties 。例如:
spring:
messages:
basename: static/i18n/messages #相对路径 开头请勿添加斜杠
然后在 classpath:/static/i18n 目录中添加如下国际化文件:
默认文件:messages.properties
#这里填写默认翻译,内容可以留空,但文件必须存在。
美式英语:messages_en_US.properties
#这里填写英语翻译。
user.title=User Login
user.welcome=Welcome
user.username=Username
user.password=Password
user.login=Sign In
中文简体:messages_zh_CN.properties
#这里填写中文翻译
user.title=用户登陆
user.welcome=欢迎
user.username=登陆用户
user.password=登陆密码
user.login=登陆
中文繁体:messages_zh_TW.properties
#这里填写繁体翻译
user.title=用戶登陸
user.welcome=歡迎
user.username=登陸用戶
user.password=登陸密碼
user.login=登陸
3、代码国际化
通过工具类的静态方法MessageUtils.get("user.title") 快速获取当前国际化的翻译值。
/**
* 国际化工具类
*/
@Component
public class MessageUtils{
private static MessageSource messageSource;
public MessageUtils(MessageSource messageSource) {
FastLocale.messageSource = messageSource;
}
/**
* 获取单个国际化翻译值
*/
public static String get(String msgKey) {
try {
return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
} catch (Exception e) {
return msgKey;
}
}
二、页面国际化
首先在pom文件引入Thymeleaf和Web依赖,然后在页面中只需通过th:xx="#{x.label}"即可获取对应的国际化翻译值。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
例如:
<title th:text="#{user.title}">用户登陆</title>
三、JS国际化
首先在pom文件引入jQuery、jquery-properties-i18n等依赖,然后在初始化后即可通过JS函数获取对应国际化文件的内容。
<dependency><!--webjars版本定位器 用于省略版本号-->
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency><!--jQuery前端依赖-->
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency><!--jQuery国际化插件-->
<groupId>org.webjars.bower</groupId>
<artifactId>jquery-i18n-properties</artifactId>
<version>1.2.7</version>
</dependency>
例如:为了提高可用性 这里提供了获取当前国际化语言和获取国际化翻译的方法。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{user.title}">用户登陆</title>
<script th:src="@{/webjars/jquery/jquery.min.js}"></script>
<script th:src="@{/webjars/jquery-i18n-properties/jquery.i18n.properties.min.js}"></script>
<script th:inline="javascript">
//获取应用路径
var ROOT = [[${#servletContext.contextPath}]];
//获取默认语言
var LANG_COUNTRY = [[${#locale.language+'_'+#locale.country}]];
//初始化i18n插件
$.i18n.properties({
path: ROOT + '/i18n/',//这里表示访问路径
name: 'messages',//文件名开头
language: LANG_COUNTRY,//文件名语言 例如en_US
mode: 'both'//默认值
});
//初始化i18n函数
function i18n(msgKey) {
try {
return $.i18n.prop(msgKey);
} catch (e) {
return msgKey;
}
}
//获取国际化翻译值
console.log(i18n('user.title'));
console.log(i18n('User Login'));
</script>
</head>
<body>
<div class="logo_box">
<select id="locale">
<option value="zh_CN">中文简体</option>
<option value="zh_TW">中文繁体</option>
<option value="en_US">English</option>
</select>
<h3 th:text="#{user.welcome}">欢迎登陆</h3>
<form>
<div class="input_outer">
<span class="u_user"></span>
<input id="username" name="username" class="text" type="text" th:placeholder="#{user.username}">
</div>
<div class="input_outer">
<span class="us_uer"></span>
<input id="password" name="password" class="text" type="password" th:placeholder="#{user.password}">
</div>
<div class="mb2">
<a class="act-but submit" th:text="#{user.login}">登录</a>
</div>
</form>
</div>
<script th:inline="javascript">
//选中语言
$("#locale").find('option[value="' + LANG_COUNTRY + '"]').attr('selected', true);
//切换语言
$("#locale").change(function () {
$.get(ROOT + '/?lang=' + $("#locale").val(), function () {
location.reload();
});
});
</script>
</body>
</html>
关于i18n插件的更多配置项请查阅 jquery-properties-i18n 官方文档。
四、语言切换
很多新人配置好之后不懂得如何切换国际化语言,其实很简单,由于在前面已经配置了拦截器LocaleChangeInterceptor ,此时我们只需在任意请求中附上语言参数lang即可,当然也通过AJAX来快速切换。
例如:
默认英语:http://http://127.0.0.1:8080?lang=en_US
中文简体:http://http://127.0.0.1:8080?lang=zh_CN
中文繁体:http://http://127.0.0.1:8080?lang=zh_TW
五、工程演示
英文界面

中文界面

好用的框架随处可见,高效的整合万里挑一,关注作者,关注SpringBoot,让Java编程更简单!!
作者:yizhiwazi
链接:https://www.jianshu.com/p/e2eae08f3255
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
SpringBoot 快速支持国际化i18n的更多相关文章
- Spring使用拦截器支持国际化(转)
Spring使用拦截器支持国际化很方便,使用时只需要两个步骤: 一.spring配置 具体配置方式如下: <!-- 资源文件绑定器,文件名称:messages.properties(没有找到时的 ...
- springMVC项目国际化(i18n)实现方法
SpringMVC项目国际化(i18n)实现方法 按照作息规律,每周五晚必须是分享知识的时间\(^o^)/~,这周讲点儿啥呢,项目需要逼格,咱们国际化吧(* ̄rǒ ̄)~,项目中碰到这类需求的童鞋可能并 ...
- SpringData 基于SpringBoot快速入门
SpringData 基于SpringBoot快速入门 本章通过学习SpringData 和SpringBoot 相关知识将面向服务架构(SOA)的单点登录系统(SSO)需要的代码实现.这样可以从实战 ...
- springboot快速使用
1.编写SpringConfig 用于实例化Spring容器 @Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件 @Bean // 通过该注解来表明是 ...
- 使用Springboot快速搭建SSM框架
Spring Boot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 一.环境准备 Idea 2017 或 201 ...
- 让QT/Embedded支持国际化
让QT/Embedded支持国际化 环境配置: Qt/Embedded ,在主机和目标板上存放路径都为:/root/qt-embedded-free- Qt/X11 3.3 (主要用到其中的lupda ...
- spring 国际化i18n配置
i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称.在资讯领域,国际化(i18n)指让产品(出版物,软件,硬件等)无需做大的改 ...
- spring 国际化-i18n
i18n(其 来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称.在资讯领域,国际化(i18n)指让产品(出版 物,软件,硬件等)无需做大 ...
- SPRING-BOOT系列之SpringBoot快速入门
今天 , 正式来介绍SpringBoot快速入门 : 可以去如类似 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/refer ...
随机推荐
- tensorboard可视化(先写一点点)
在tensorboard上显示运行图: import tensorflow as tf a = tf.constant(10,name="a") b = tf.constant(9 ...
- iText导出PDF(图片,水印,页眉,页脚)
项目需要导出PDF,导出的内容包含图片和文本,而且图片的数量不确定,在网上百度发现大家都在用iText,在官网发现可以把html转换为PDF,但是需要收费,那就只能自己写了. 在开始之前先在网上百度了 ...
- js执行上下文与执行上下文栈
一.什么是执行上下文 简单说就是代码运行时的执行环境,必须是在函数调用的时候才会产生,如果不调用就不会产生这个执行上下文.在这个环境中,所有变量会被事先提出来(变量提升),有的直接赋值,有的为默认值 ...
- python学习笔记(十五)python操作数据库
1.连接mysql,ip,端口号,密码,账号,数据库 2.建立游标 3.执行sql 4.获取结果 5.关闭连接,关闭游标 游标打开仓库的大门: import pymysql conn=pymysql. ...
- 使用 pyenv 管理 Python 版本
http://einverne.github.io/post/2017/04/pyenv.html Posted on 04/22/2017 by Ein Verne | View revisio ...
- php str_ireplace()函数 语法
php str_ireplace()函数 语法 作用:字符串替换操作,不区分大小写 语法:str_ireplace(find,replace,string,count)大理石平台规格 参数: 参数 描 ...
- 定义一个JobService,开启本地服务和远程服务
@SuppressWarnings(value = ["unchecked", "deprecation"])@RequiresApi(Build.VERSIO ...
- Linux C编程
Linux C网络编程 1.Linux套接字 1.1 套接字介绍 套接字(Sockets),即为网络进程ID,是由运行这个进程的计算机的IP地址和这个进程使用的端口(Port)组成. 可以只用'net ...
- 浅谈JSONObject解析JSON数据
我们在做jmeter接口测试时能会用beanshell断言,一般都会将返回值转成JSONObject对象进行处理.本文选取较为复杂json格式数据,也将适用于java接口测试. JSON数据 { &q ...
- reuseaddr和点对点聊天
解决绑定失败 在测试时,经常会出现绑定错误,bind error: Address already in use 这里只要指定一下socket的reuseaddr属性即可解决 int on=1; if ...